LoginSignup
10
16

More than 3 years have passed since last update.

Powershellコンソールエラーを非表示にする方法

Last updated at Posted at 2017-09-12

PowerShell でスクリプトを書いていてエラーをコンソールに表示しない方法を
色々調べたが、中々解決できなかったので自分向けの備忘録も兼ねて投稿

やりたいこと

  • PowerShell でエラーをコンソールに表示しないようにする
  • この方法を使用しても結果は $error に格納されている

作業

  • コンソールにエラーを表示させない場合
PS> $ErrorActionPreference = "silentlycontinue"
  • エラーを表示させるように戻す場合
PS> $ErrorActionPreference = "continue"

使用例

PS C:\Users\Administrator> ls -l
Get-ChildItem : パラメーター 'LiteralPath' の引数が指定されていません。型 'System.String[]' のパラメーターを指定し、再試行してください。
発生場所 行:1 文字:4
+ ls -l
+    ~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem]、ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.GetChildItemCommand

PS C:\Users\Administrator> $ErrorActionPreference = "silentlycontinue"
PS C:\Users\Administrator> ls -l
PS C:\Users\Administrator> $ErrorActionPreference = "continue"
PS C:\Users\Administrator> ls -l
Get-ChildItem : パラメーター 'LiteralPath' の引数が指定されていません。型 'System.String[]' のパラメーターを指定し、再試行してください。
発生場所 行:1 文字:4
+ ls -l
+    ~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem]、ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.GetChildItemCommand

個人的感想

  • ps1 のスクリプト内の処理でも使用できるので便利!!
  • $変数 = command 2>&1 で変数に標準出力/標準エラー出力を格納したかったがコンソールに表示されてしまったので最後の手段として使用した

参考URL

10
16
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
10
16