![](/img/trans.png)
[英]Copy folders without files, files without folders, or everything using PowerShell
[英]Zip multiple folders and files using powershell 2
我有以下文件夾、子文件夾和文件的結構 C:\\Prod\\FolderName1 C:\\Prod\\FolderName1XX C:\\Prod\\FolderName1YY C:\\Prod\\FolderName1ZZ
我想將所有 Foldername1 文件夾及其子文件夾和文件壓縮到一個 zip 文件中。
以下適用於 powershell 5.0
$name = Read-Host 'enter the folder NAME'
$namexx = $name + 'xx'
$nameyy = $name + 'yy'
$namezz = $name + 'zz'
$fullpath = join-path -path 'C:\Prod\' -childpath $name
$fullpathxx = join-path -path 'C:\Prod\' -childpath $namexx
$fullpathyy = join-path -path 'C:\Prod\' -childpath $nameyy
$fullpathzz = join-path -path 'C:\Prod\' -childpath $namezz
Compress-Archive -LiteralPath $fullpath,$fullpathxx,$fullpathyy,$fullpathzz -CompressionLevel Optimal -DestinationPath "C:\Dev\$blue $(get-date -f yyyy-MM-dd).zip"
不幸的是,在必須發生這種情況的服務器上,Powershell 是 2.0 版並且沒有 Compress-Archive cmdlet。
我試過了
Add-Type -Assembly "System.IO.Compression.FileSystem" ;
[System.IO.Compression.ZipFile]::CreateFromDirectory("$fullpath", "c:\dev\$name.zip") ;
但是這種方法會為每個文件夾創建多個 zip 文件。 提前致謝。
我能夠在 2.0 中使用 DotNetZip 庫做到這一點。
您可以在此處找到您需要的所有文檔/下載:
https://archive.codeplex.com/?p=dotnetzip
要將其實現到 PS 腳本中,您需要執行以下操作:
[System.Reflection.Assembly]::LoadFrom("your \ path \ to \ the \ dll \ file")
#To zip a file, do this:
$zipObj = New-Object Ionic.Zip.Zipfile
$zipObj.AddFile($fileName, "file")
$zipObj.Save($saveFileName)
$zipObj.Dispose()
#To zip a directory, do this:
$zipObj = New-Object Ionic.Zip.Zipfile
$zipObj.AddDirectory($directoryName,"dir")
$zipObj.Save($saveDirectoryName)
$zipObj.Dispose()
希望這可以幫助! 我知道不得不依賴另一個工具是一種痛苦 - 但這個 dll 確實創造了奇跡(並且我們繼續使用它,即使 Powershell 4 能夠自行壓縮)。
這里還有另一個很好的例子(帶加密): https : //documentation.help/DotNetZip/Powershell.htm
編輯:Codeplex 很快就會被撤下,我討厭點擊一個已關閉的鏈接,所以如果將來有人正在尋找這個庫,你可以在這里找到它:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.