2016-03-05 105 views
1

爲什麼即使生成錯誤時PowerShell也不會捕獲語句?在這種情況下,我故意刪除數據文件夾以查看catch塊是否被調用。從PowerShell的Powershell - Catch塊即使在發生錯誤時也不會調用

Set-Content : Could not find a part of the path 'D:\Data\CUST.csv'. 
At D:\Data\Scripts\CUST_HOUSEKEPPING.ps1:55 char:79 
+ $getData2 | Where-Object{[regex]::matches($_,"\,").count -eq 22} | set-content <<<< $outPath 
+ CategoryInfo   : ObjectNotFound: (D:\Data\CUST.csv:String) [Set-Content], DirectoryNotFo 
undException 
+ FullyQualifiedErrorId : GetContentWriterDirectoryNotFoundError,Microsoft.PowerShell.Commands.SetContentCommand 

回答

1

這是在PowerShell中調用其中-ErrorAction決定了你的代碼是如何迴應的一個接收

Catch 
{ 
$ErrorMessage = $_.Exception.Message 
$FailedItem = $_.Exception.ItemName 
Send-MailMessage -From xxxxxxxxxx 
Break 
} 

此錯誤消息。

使用帶有和不帶「-ErrorAction Stop」部分的示例代碼並查看其差異。沒有,它的行爲就像你的問題。有了它,它會拋出異常。

try 
{ 
    "FOO" | Set-Content -Path 'd:\doesnotexist\file1.txt' -ErrorAction Stop 
} 
catch 
{ 
    Write-Output "Caught something..." 
} 
finally 
{ 
    Write-Output "Performing finally..." 
} 

另見about_CommonParameters

+0

'-ErrorAction Stop'是必需的,因爲錯誤是非終端(管道可以繼續工作)。 Try/catch只捕獲通常會阻止腳本/函數繼續執行的終止錯誤。 –

相關問題