【发布时间】:2016-09-23 14:00:07
【问题描述】:
我想使用 Powershell 来自动化: 1. 压缩超过 7 天的日志文件(.xml 和 .dat 扩展名), 2. 将这些压缩档案复制到别处并 3. 然后从源中删除原始日志文件。
我正在使用以下 Powershell 脚本,它是从各种资源中拼凑而成的。
function New-Zip
{
param([string]$zipfilename)
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
function Add-Zip
{
param([string]$zipfilename)
if(-not (test-path($zipfilename)))
{
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Start-sleep -milliseconds 500
}
}
$targetFolder = 'C:\source'
$destinationFolder = 'D:\destination\'
$now = Get-Date
$days = 7
$lastWrite = $now.AddDays(-$days)
Get-ChildItem $targetFolder -Recurse | Where-Object { $_ -is [System.IO.FileInfo] } | ForEach-Object {
If ($_.LastWriteTime -lt $lastWrite)
{
$_ | New-Zip $($destinationFolder + $_.BaseName + ".zip")
$_ | Add-Zip $($destinationFolder + $_.BaseName + ".zip")
}
}
Get-ChildItem $targetFolder -Recurse -Include "*.dat", "*.xml" | WHERE {($_.CreationTime -le $(Get-Date).AddDays(-$days))} | Remove-Item -Force
此脚本运行良好,因为它仅归档文件,并将它们复制到目标文件夹。
如果我的结构是 C:\source\bigfolder\logfile.dat,则生成的 zip 文件将无法获得我想要的文件夹结构:
logfile.zip>bigfolder>logfile.dat
相反,它只是得到:logfile.zip>logfile.dat
有人可以帮忙解决这个问题吗?
为了更好地对其进行微调,如果可能的话,我希望构建一些逻辑,以便仅在满足特定条件时才压缩文件。
我压缩的原始日志文件有一个如下命名例程:
Folders:
emstg#12_list\randomstring.xml
Individual log files:
emstg#12_query_data.xml
emstg#12_events_cache.dat etc...
正如您所见,这些文件的开头与 emstg#number 相同。
如何在上面的脚本中实现“名称检测”机制?
谢谢
【问题讨论】:
标签: powershell compression powershell-3.0