Home > PowerShell > PowerShell Return Codes

PowerShell Return Codes

You can access/verify/check the success/failure return code of a Powershell commands via $? variable.  The $? variable is of type Boolean. It will only give you a True or False states depending whether the last command ran successfully or failed respectively.

Checking PS commands return code:

Sample code:

$ret = Invoke-Item "C:\Program Data\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2007.lnk" # Note the space in the path which is incorrect
Write-Host "$?"
$date = get-date -format MM:dd:yyyy-HH:mm:ss
Write-Host "$?"

Output:

Invoke-Item : Cannot find path ‘C:\Program Data\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2007.lnk’ because it does not e
xist.
At C:\temp\test-ps-return-codes.ps1:2 char:19
+ $ret = Invoke-Item <<<<  "C:\Program Data\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2007.lnk"
    + CategoryInfo          : ObjectNotFound: (C:\Program Data… Excel 2007.lnk:String) [Invoke-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeItemCommand
False
True

Making use of $? return code:

Sample code:

$ret = Invoke-Item "C:\Program Data\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2007.lnk" # Note the space in the path which is incorrect
if($?) {
    Write-Host "Successfully Invoked Excel 2007"
} else {
    Write-Host "Failed to Invoke Excel 2007"
}

 

Output:

Invoke-Item : Cannot find path ‘C:\Program Data\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2007.lnk’ because it does not e
xist.
At C:\temp\test-ps-return-codes.ps1:2 char:19
+ $ret = Invoke-Item <<<<  "C:\Program Data\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2007.lnk"
    + CategoryInfo          : ObjectNotFound: (C:\Program Data… Excel 2007.lnk:String) [Invoke-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeItemCommand
Failed to Invoke Excel 2007

Categories: PowerShell
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 96 other followers