2017-06-22 68 views
1

我正在構建一個腳本,該腳本的Try statementTry塊和多個Catch塊。 PowerShell中的This page has provided a good guide to help with identifying error types以及如何在catch語句中處理它們。可能使用寫入錯誤指定錯誤類型,還是僅使用throw?

到目前爲止,我一直在使用Write-Error。我認爲可以使用其中一個可選參數(CategoryCategoryTargetType)來指定錯誤類型,然後使用專門用於該類型的catch塊。

不幸運:該類型始終列爲Microsoft.PowerShell.Commands.WriteErrorException
throw給了我究竟是什麼。

代碼

[CmdletBinding()]param() 

Function Do-Something { 
    [CmdletBinding()]param() 
    Write-Error "something happened" -Category InvalidData 
} 

try{ 
    Write-host "running Do-Something..." 
    Do-Something -ErrorAction Stop 

}catch [System.IO.InvalidDataException]{ # would like to catch write-error here 
    Write-Host "1 caught" 
}catch [Microsoft.PowerShell.Commands.WriteErrorException]{ # it's caught here 
    Write-host "1 kind of caught" 
}catch{ 
    Write-Host "1 not caught properly: $($Error[0].exception.GetType().fullname)" 
} 


Function Do-SomethingElse { 
    [CmdletBinding()]param() 
    throw [System.IO.InvalidDataException] "something else happened" 
} 

try{ 
    Write-host "`nrunning Do-SomethingElse..." 
    Do-SomethingElse -ErrorAction Stop 

}catch [System.IO.InvalidDataException]{ # caught here, as wanted 
    Write-Host "2 caught" 
}catch{ 
    Write-Host "2 not caught properly: $($Error[0].exception.GetType().fullname)" 
} 

輸出

running Do-Something... 
1 kind of caught 

running Do-SomethingElse... 
2 caught 

我的代碼是做我想要的東西;當throw完成這項工作時,它不一定是Write-Error。我想了解的是:

  • 是否可以指定與Write-Error A型(或以其他方式Write-Error錯誤區分),使它們可以在不同catch塊來處理?

N.B.我知道$Error[1] -like "something happen*"和處理使用if/else塊是一個選項。

Closest related question I could find on SO - Write-Error v throw in terminating/non-terminating context

回答