5

例外をスローするコードがある場合、エラー メッセージが表示されますが、スローされている例外を正しくキャッチ (または判断) する方法がわかりません。通常、私はそれをキャッチしますSystem.Exceptionが、これは悪い考えです。

以下に例を示します...存在しないドライブにフォルダを作成しようとしています:

PS <dir> .\myScript.ps1 z:\test
mkdir : Cannot find drive. A drive with the name 'z' does not exist.
At <dir>myScript.ps1:218 char:7
+       mkdir $args[0] 1> $null
+       ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (z:String) [New-Item], DriveNotFoundExc
   eption
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemComm
   and

をキャッチしようとしましSystem.DriveNotFoundExceptionたが、スクリプトを再実行すると、まだキャッチされていない例外が発生します。

あらゆる種類の例外を効果的に処理するためのヒントはありますか?

4

1 に答える 1

5

コマンドを実行した直後に、$error[0] の内容を調べます。Exception プロパティを見てください。

$error[0] | fl * -force

writeErrorStream      : True
PSMessageDetails      :
Exception             : System.Management.Automation.DriveNotFoundException: Cannot find drive. A drive with the name
                        'z' does not exist.
                           at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean
                        automount)
                           at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean

その特定の例外は[System.Management.Automation.DriveNotFoundException].

ところで、その例外を「キャッチ」したい場合は、キャッチできる例外を生成するために -EA Stop を使用して非終了エラーを終了エラーに変換する必要があります。

PS> try {mkdir z:\foo -ea Stop} catch {$_.Exception.GetType().FUllname}
System.Management.Automation.DriveNotFoundException
于 2013-10-01T14:02:25.367 に答える