2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【PowerShell】コマンド実行の成功/失敗を取り出す方法

Posted at

はじめに

コマンド実行の成功/失敗を取り出す方法についてアウトプットします。
※最近、業務でPowerShellスクリプトを書く中で使用している手法になります。

コマンド実行の成功/失敗の結果を取り出す

こちらのコマンドを利用します。

command
echo $?

成功の場合の出力

成功
PS C:\Users\owner> Get-Host


Name             : Windows PowerShell ISE Host
Version          : 5.1.18362.752
InstanceId       : ae3418e2-425d-473d-aa82-c44f35743808
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : ja-JP
CurrentUICulture : ja-JP
PrivateData      : Microsoft.PowerShell.Host.ISE.ISEOptions
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

PS C:\Users\owner> 
PS C:\Users\owner> echo $?
True ←「True」はコマンド実行に成功したという意味

失敗の場合の出力

失敗
PS C:\Users\owner> aaa
aaa : 用語 'aaa' は、コマンドレット、関数、スクリプト ファイル、または操作可能なプログラムの名前として認識されません。名前が正しく記述されていることを確認し、パスが含まれている場合はそのパスが正しいことを確認してから、再試行してください。
発生場所 :1 文字:1
+ aaa
+ ~~~
    + CategoryInfo          : ObjectNotFound: (aaa:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 

PS C:\Users\owner> 
PS C:\Users\owner> echo $?
False ← 「False」はコマンド実行に失敗したという意味

使用方法(例)

①「if」にて条件式にしてみる

  • code
例1
Get-Host | Out-Null
$result = echo $?

if($result -eq "True"){
  Write-Host "コマンドの実行に成功しました。"
}else{
  Write-Host "コマンドの実行に失敗しました。"
}
  • 実行結果
実行結果
PS C:\Users\owner> C:\Users\owner\Desktop\scripts\command.ps1
コマンドの実行に成功しました。

PS C:\Users\owner> 

②「foreach」でやってみる

  • code
例2
$commands = @("Get-Host","Get-NetAdapter","Get-DnsClientServerAddress")
$results = @()

foreach($command in $commands){
  powershell $command | Out-Null
  $results += echo $?
}

foreach($result in $results){
  Write-Host $result
}
  • 実行結果
実行結果
PS C:\Users\owner> C:\Users\owner\Desktop\scripts\command.ps1
True
True
True

PS C:\Users\owner> 
2
3
0

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?