我试图将单个目录中的所有文件压缩到不同的文件夹,作为简单备份例程的一部分。
代码运行正常,但不会生成zip文件:
$srcdir = "H:\Backup" $filename = "test.zip" $destpath = "K:\" $zip_file = (new-object -com shell.application).namespace($destpath + "\"+ $filename) $destination = (new-object -com shell.application).namespace($destpath) $files = Get-ChildItem -Path $srcdir foreach ($file in $files) { $file.FullName; if ($file.Attributes -cne "Directory") { $destination.CopyHere($file, 0x14); } }
任何想法,我要去错了?
这在V2中工作,也应该在V3中工作:
$srcdir = "H:\Backup" $zipFilename = "test.zip" $zipFilepath = "K:\" $zipFile = "$zipFilepath$zipFilename" #Prepare zip file if(-not (test-path($zipFile))) { set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) (dir $zipFile).IsReadOnly = $false } $shellApplication = new-object -com shell.application $zipPackage = $shellApplication.NameSpace($zipFile) $files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer} foreach($file in $files) { $zipPackage.CopyHere($file.FullName) #using this method, sometimes files can be 'skipped' #this 'while' loop checks each file is added before moving to the next while($zipPackage.Items().Item($file.name) -eq $null){ Start-sleep -seconds 1 } }
我发现了另外两种方法来做到这一点,包括他们作为参考:
使用.Net框架4.5(由@MDMarrabuild议):
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) [System.AppDomain]::CurrentDomain.GetAssemblies() $src_folder = "h:\backup" $destfile = "k:\test.zip" $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal $includebasedir = $false [System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder, $destfile, $compressionLevel, $includebasedir)
这在我的Win7开发机器上效果很好,可能是最好的方法,但是.Net 4.5只支持Windows Server 2008(或更高版本),我的部署机器是Windows Server 2003。
使用命令行压缩工具:
function create-zip([String] $aDirectory, [String] $aZipfile) { [string]$PathToZipExe = "K:\zip.exe"; & $PathToZipExe "-r" $aZipfile $aDirectory; } create-zip "h:\Backup\*.*" "K:\test.zip"
我下载了info-zip ,并将其与源和目标位置作为参数进行了调用。
这工作得很好,很容易设置,但需要一个外部的依赖。