为什么即使出现错误,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
答案 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..."
}