Ste*_*teB 4 powershell compression
作为简单备份例程的一部分,我正在尝试将单个目录中的所有文件压缩到不同的文件夹中。
代码运行正常,但不生成 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);
}
}
Run Code Online (Sandbox Code Playgroud)
任何想法我哪里出错了?
这适用于 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
}
}
Run Code Online (Sandbox Code Playgroud)
我发现了另外两种方法来做到这一点,并将它们包括在内以供参考:
使用 .Net 框架 4.5(如@MDMarra 所建议):
[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)
Run Code Online (Sandbox Code Playgroud)
这在我的 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"
Run Code Online (Sandbox Code Playgroud)
我下载了info-zip并使用源位置和目标位置作为参数调用它。
这工作得很好并且很容易设置,但需要外部依赖。
归档时间: |
|
查看次数: |
26162 次 |
最近记录: |