LoginSignup
1
0

More than 5 years have passed since last update.

Remove-Item に -Verbose を指定すると ErrorActionPreference が無効になる

Last updated at Posted at 2017-12-23
テストコード
$ErrorActionPreference = "Stop"

# 存在しないファイル
$file = "aaa.log"

try {
    "Remove-Item $file" | Out-Host
    Remove-Item $file
} catch {
    "エラー発生1" | Out-Host
}

try {
    "Remove-Item $file -Verbose" | Out-Host
    Remove-Item $file -Verbose
} catch {
    "エラー発生2" | Out-Host
}

try {
    "Remove-Item $file -Verbose -ErrorAction Stop" | Out-Host
    Remove-Item $file -Verbose -ErrorAction Stop
} catch {
    "エラー発生3" | Out-Host
}

"処理終了" | Out-Host
実行結果
Remove-Item aaa.log
エラー発生1
Remove-Item aaa.log -Verbose
Remove-Item : パス 'C:¥aaa.log' が存在しないため検出できません。
発生場所 C:¥Users¥nonaka¥Desktop¥remove-item_error.ps1:15 文字:5
+     Remove-Item $file -Verbose
+     ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
    + CategoryInfo          : ObjectNotFound: (C:¥aaa.log:String) [Remove-Item 
   ], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.Remov 
   eItemCommand

Remove-Item aaa.log -Verbose -ErrorAction Stop
エラー発生3
処理終了

Remove-Item-Verboseを指定すると、$ErrorActionPreferenceStopを指定しているのに、2番目のように例外がキャッチできなくなる。3番目のように-ErrorAction Stopを個別に指定すると例外がキャッチできる。

Copy-Item-Verbose指定しても、この現象は起きない。改めて確認したところ、Copy-Itemでも同じ現象が発生した。特定のコマンドレットによらない模様。(詳細はコメント欄参照。)

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0