7

存在しないファイルに対して次のスクリプトを実行すると、何らかの理由でスクリプトが例外をキャッチしません。このコードは、Webで見つけた例に基づいていますが、うまくいかないようです。

これを修正する方法についてのヒントやポインタをいただければ幸いです。

注:以下の例では、私も試しました

trap [Exception] {

しかし、それもうまくいきませんでした。

スクリプトは次のとおりです。

function CheckFile($f) {

      trap {
        write-host "file not found, skipping".
        continue
      }

      $modtime = (Get-ItemProperty $f).LastWriteTime

      write-host "if file not found then shouldn't see this"
}


write-host "checking a file that does not exist"
CheckFile("C:\NotAFile")
write-host "done."

出力:

PS > .\testexception.ps1
checking a file that does not exist
Get-ItemProperty : Cannot find path 'C:\NotAFile' because it does not exist.
At C:\Users\dleclair\Documents\Visual Studio 2010\lib\testexception.ps1:12 char:35
+       $modtime = (Get-ItemProperty <<<<  $f).LastWriteTime
    + CategoryInfo          : ObjectNotFound: (C:\NotAFile:String) [Get-ItemProperty], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand

if file not found then shouldn't see this
done.
PS >
4

2 に答える 2

6

このようにしてみてください:

trap { write-host "file not found, skipping";continue;}
$modtime = Get-ItemProperty c:\manoj -erroraction stop

OPからのコメントに基づく:

リンク先の記事で言われていることを誤解していると思います。

この例では、実行を続行して、トラップが存在するスコープに戻り、次のコマンドを実行します。実行はトラップのスコープにのみ戻ることに注意することが重要です。そのため、例外が関数内または if ステートメント内でスローされ、その外でトラップされた場合は、ネストされたスコープの最後で続行が取得されます。 .

したがって、次のようなことをすると:

trap{ write-host $_; continue;}
throw "blah"
write-host after

after印刷されます。

しかし、次のようなことをすると:

trap{ write-host $_ ; continue}
function fun($f) {


      throw "blah"
      write-host after
}

fun
write-host "outside after"

after印刷されませんが、印刷されoutside afterます。

または、try-catch ブロックを使用します。

      try{
      $modtime = (Get-ItemProperty $f -erroraction stop).LastWriteTime
      write-host "if file not found then shouldn't see this"
      }
      catch{
        write-host "file not found, skipping".
      }
于 2011-08-26T03:51:01.413 に答える
0

機能させるには、関数の内側またはスクリプトの外側 (グローバル アプリケーションの場合) に設定$ErrorActionPreferenceする必要があります。または(前述のように)、共通パラメータを同じものに設定します。SilentlyContinuetrap-ErrorAction

于 2011-08-29T14:54:20.083 に答える