hakeの日記

Windows環境でプログラミングの勉強をしています。

PowerShell - 例外処理

try節のブロックで例外が発生した場合、(該当する型を記述した)catch節が実行される。finally節は例外発生有無に関わらず実行される。

try { 
    "try節です"
    1/0
}
catch [Exception] {
    "catch節です"
}
finally {
    "finary節です"
}
try節です
catch節です
finary節です


発生した例外の情報は$Errorに格納される、直近で発生した例外は要素0で参照可能です。

PS C:\> $error[0]
0 で除算しようとしました。
発生場所 行:3 文字:5
+     1/0
+     ~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException


PS C:\> $error[0].CategoryInfo

Category   : NotSpecified
Activity   : 
Reason     : RuntimeException
TargetName : 
TargetType : 


PS C:\> $error[0].Exception
0 で除算しようとしました。

PS C:\> $error[0].FullyQualifiedErrorId
RuntimeException

PS C:\> $error[0].InvocationInfo

MyCommand             : 
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 3
OffsetInLine          : 5
HistoryId             : -1
ScriptName            : 
Line                  :     1/0
                        
PositionMessage       : 発生場所 行:3 文字:5
                        +     1/0
                        +     ~~~
PSScriptRoot          : 
PSCommandPath         : 
InvocationName        : 
PipelineLength        : 0
PipelinePosition      : 0
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :