$LASTEXITCODE and $? In Powershell

      No Comments on $LASTEXITCODE and $? In Powershell

Its a powershell built-in variables that tells if last command/script executed successfully or failed. Its used to perform error handlingse either in scripts or from command lines easily.

$LASTEXITCODE:
This is equivalent to %errorlevel% variable in cmd shell. When you execute a command in cmd.exe the execution status is stored in %errorlevel% variable which can be used in batch scripting to determine the execution status of previous command. Generally a zero(0) value in $LASTEXITCODE is treated as success and any other non-zero are treated as failures

The $? Variable:
This is another built-in variable in Powershell which has the same functionality of $LASTEXITCODE except that it stores the execution status of last powershell command AND win32 applications execution status. You can use this in Powershell scripts or while executing one-liners from powershell console. This variable won’t tell the return code, but it tells you whether the last PS command or Win32 executable executed successfully or not. That means, it will contain either of two values, $TRUE or $FALSE. When a command is executed successfully, this variable value is changed to $TRUE. Similarly, it is changed to $FALSE when the last PS command is failed.

Thanks

WintelAdmin

Print Friendly, PDF & Email

Leave a Reply

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