我在powershell脚本中遇到问题,它会过滤最近24到25小时的文件并压缩所有这些罚款并准备备份上传?

时间:2016-05-11 12:37:03

标签: powershell scripting

$source = "C:\folder\*.*"
$destination = "C:\folder3\test.zip"
$results = (Get-ChildItem -Path $source -Filter *.* | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-1)) 
}  
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($results, $destination) 

现在我需要选择最后修改过的文件并通过压缩或7zip压缩拉链?

2 个答案:

答案 0 :(得分:0)

要通过Powershell压缩文件,我通常会在系统上安装7-zip,然后在脚本中包含此功能:

#7-ZIP FILE FUNCTION (must install 7-zip on system)
#-------------------------------------------------------------------------------------
#
function ZipFile7 ([string] $pZipFile, [string] $pFiles) { 
    $7zipExe = "$($env:programfiles)\7-Zip\7z.exe"
    $7zArgs = @("a", "-tzip", $pZipFile, $pFiles, "-r")
    & $7zipExe $7zArgs    
} 
#-------------------------------------------------------------------------------------

$pZipFile是您要创建的文件的完整路径,$pFiles是您要压缩的文件的路径(可以包含C:\*.txt等通配符)。

答案 1 :(得分:0)

$source = "C:\folder\*.*"
$destination = "C:\folder3\test.zip"
$results = Get-ChildItem -Path $source | Where {$_.LastWriteTime -gt (Get-Date).AddDays(-1)} | Select -ExpandProperty "FullName"
set-content $destination ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
$Shell = New-Object -Com Shell.Application
$ZipFile = $Shell.Namespace($destination)
$Results | ForEach {
    $Count = $ZipFile.Items().Count
    $ZipFile.CopyHere($_)
    While ($ZipFile.Items().Count -eq $Count) {Start-Sleep -Milliseconds 200} # Wait till the file is zipped
}

注意:您可能希望改进while / wait语句(例如设置超时),因为如果将文件复制到zip文件夹有任何问题,它可能会挂起。