2013-08-06 93 views
2

這是我的代碼,這是非常簡單的:一個簡單的try/catch不工作

$TargetFolder = 'M:\' 

try{ 

$Getfolderlist = Get-ChildItem $TargetFolder -Recurse | ? { $_.PSIsContainer -and $_.Name -eq 'old' } 

}catch { 

Write-Host "Error ! :) "  

} 

它不工作,我得到一個PowerShell的例外:

Get-ChildItem : Cannot find drive. A drive with the name 'M' does not exist. 
At C:\ef-scripts\PurgeDeliveryZip\purge_delivery_zip.ps1:23 char:18 
+ $Getfolderlist = Get-ChildItem $TargetFolder -Recurse | ? { $_.PSIsContainer -an ... 
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (M:String) [Get-ChildItem], DriveNotFoundException 
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand 

謝謝您幫幫我。

回答

7

您需要將-ErrorAction設置爲Stop。這樣catch塊得到異常。請閱讀關於try catch的使用方法:http://technet.microsoft.com/en-us/library/hh847793.aspx

此外,您可能想了解有關在PowerShell中終止錯誤和ErrorAction常見參數的幫助。

$TargetFolder = 'M:\' 

try{ 
$Getfolderlist = Get-ChildItem $TargetFolder -Recurse -Ea Stop | ? { $_.PSIsContainer -and $_.Name -eq 'old' } 
} 
catch { 
Write-Host "Error ! :) "  
}