Hi I'm noticing some odd behavior with the following code snippet
function test
{
$LASTEXITCODE = $null
ping asdfs
Write-Host "Last exitcode: $LASTEXITCODE"
}
test
Write-Host "Last exitcode: $LASTEXITCODE"
The output from this is
Ping request could not find host asdfs. Please check the name and try again.
Last exitcode:
Last exitcode: 1
Why is $LASTEXITCODE not set within the test() function?
This is a generalization of a problem I'm having right now, when I call a Win32 .exe from within a function and the $LASTEXITCODE isn't returning the value I'm expecting from within a function
Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.
The proper reliable way to return a value from a script function is through setting a variable. Relying on the position of output is prone to breakage in the future if someone for example adds new output to the streams; Write-Output/Write-Warning/Write-Verbose, etc...
$? Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed. For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.
The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.
Because you are not supposed to be setting automatic variables like that. You are creating a local variable and nullifying it. Remove the $LASTEXITCODE = $null
line and you will get the expected result. Or you can do $global:LASTEXITCODE = $null
You are assigning a value to $LASTEXITCODE inside the scope of the function test, where it actually is set. The last line of output lists $LASTEXITCODE as 1, because you left the scope of the function test and the value assigned to $LASTEXITCODE inside that scope is not of any interest anymore.
As manojlds already pointed out you can just set the variable globally, if you want to achieve that result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With