Powershell - 即使出现错误,Catch块也不会调用

时间:2016-03-05 06:08:27

标签: powershell

为什么即使出现错误,powershell也不会落入catch语句?在这种情况下,我故意删除Data文件夹以查看是否将调用catch块。

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

从powershell

收到此错误消息
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 个答案:

答案 0 :(得分:3)

这是PowerShell中的一个调用,-ErrorAction确定代码的响应方式。

使用带有和不带“-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