[英]Several folders into a zip with PowerShell
我有幾個文件夾dir_01
、 dir_02
、 dir_03
,我想備份到一個 zip 文件中,比如backup.zip
。 這必須保存在具有今天日期的文件夾中。 我需要一個 .bat 文件來完成這項工作; 不允許額外的第三方可執行文件。
在這里,我找到了如何使用今天的日期創建文件夾,但是我在將$destination
傳遞給-DestinationPath
時遇到了問題。 我創建了一個調用 PowerShell 的 .bat。 代碼給我的問題:
powershell.exe $destination = New-Item -Path 'C:\path\to\destionation' -ItemType Directory -Name ("$(Get-Date -f yyyy-MM-dd)")
powershell.exe -nologo -noprofile -command Compress-Archive -Path 'C:\path\dir_01', 'C:\path\dir_02', 'C:\path\dir_03' -DestinationPath $destination\backup.zip -Force
錯誤消息如下:
New-Object : Exception calling ".ctor" with "2" argument(s): "Access to the path 'C:\backup.zip' is denied."
At
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:729
char:30
+ ... ileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
但是,如果我對目的地的路徑進行硬編碼,則代碼有效,如下所示:
powershell.exe -nologo -noprofile -command Compress-Archive -Path 'C:\path\dir_01', 'C:\path\dir_02', 'C:\path\dir_03' -DestinationPath 'C:\whole\path\backup.zip' -Force
但是這樣做,我無法將backup.zip
保存在今天的文件夾中。
問題:如何將backup.zip
保存在我使用今天創建的文件夾中?
您可以在同一個 PowerShell 會話中執行這兩個命令,方法是用分號分隔它們。
powershell.exe $destination = New-Item -Path 'C:\path\to\destionation' -ItemType Directory -Name ("$(Get-Date -f yyyy-MM-dd)"); Compress-Archive -Path 'C:\path\dir_01', 'C:\path\dir_02', 'C:\path\dir_03' -DestinationPath $destination\backup.zip -Force
這將啟動 PowerShell 並讓它創建文件夾,然后在同一個會話中將內容壓縮到其中,而不是創建一個會話,在該會話中創建一個文件夾,關閉會話,啟動一個新的 PowerShell 會話,壓縮內容,關閉第二屆會議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.