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 DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft 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 DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft Office Excel 2007.lnk’ because it does not e
xist.
At C:temptest-ps-return-codes.ps1:2 char:19
+ $ret = Invoke-Item <<<<  "C:Program DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft 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 DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft 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 DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft Office Excel 2007.lnk’ because it does not e
xist.
At C:temptest-ps-return-codes.ps1:2 char:19
+ $ret = Invoke-Item <<<<  "C:Program DataMicrosoftWindowsStart MenuProgramsMicrosoft OfficeMicrosoft 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

Leave a Reply

Your email address will not be published. Required fields are marked *