2011-11-25 24 views
2

我從來沒有做過Powershell。在做了一些研究之後,我寫了一個腳本來壓縮一個文件夾。在PowerShell中抓取一個文件夾的錯誤

我想確保我可以捕獲執行過程中產生的任何錯誤,所以我添加了一個Try Catch塊,並試圖記錄所有錯誤。我需要確保壓縮過程是成功的。

此腳本假設我們可以添加到現有的zip文件(如果它已經存在)。稍後,我將添加一個檢查來刪除以前的zip文件,但現在如果我留下一些東西來測試日誌記錄,因爲它會產生錯誤。

但是,錯誤未按預期捕獲和記錄。任何關於我在做什麼的錯誤?該錯誤是一個彈出窗口「此文件夾已包含名爲‘備份’文件夾重命名你要複製,然後再執行操作的文件夾

######################################################## 
# 
# Zip-Folder.ps1 
# 
# Usage: 
# To zip up a folder: 
# (Zip Application) (Target Archive path and File Name) (Source Folder Path to Backup)  (Log Path and File Name) 
# d:\zip-folder.ps1 d:\Backups_Archive d:\Backups 
######################################################## 

try{ 
$target = $args[0] 
$files = Get-item $args[1] 
$log = $args[2] 


if (-not $target.EndsWith('.zip')) {$target += '.zip'} 

if (-not (test-Path $target)) { 
    set-content $target ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
} 

$ZipFile = (new-object -com shell.application).NameSpace($target) 
# $files | foreach {$zipfile.CopyHere($_.fullname)} 

foreach($file in $files) 
    { 
     $zipfile.CopyHere($file.FullName) 
      Start-sleep -milliseconds 500 
    } 
} catch { 
    Add-Content $log $error[0] 

} 

執行:。 (郵編應用)(目標歸檔路徑和文件名)(源文件夾備份路徑)(日誌路徑和文件名) 例如 d:\ zip-folder.ps1 d:\ Backups_Archive d:\ Backups d:\ zip.log

回答

3

您看到的彈出窗口是由Shell生成的,儘管you can suppress the UI by passing the flag 1024,我認爲它不可能作爲一個可以在Powershell中捕獲的錯誤處理,因爲Shell不會把它變成Powershell。您將不得不明確處理此案件,而不是發現錯誤。

此外,it is generally accepted that this way of zipping files is not really very flexible也並沒有真正與大量的文件(另一點是,你在你的代碼有睡眠)

請使用命令行的一些工具荏苒像7z.exe爲荏苒規模。

相關問題