Powershell: $LASTEXITCODE in a function Powershell: $LASTEXITCODE in a function powershell powershell

Powershell: $LASTEXITCODE in a function


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.


Not sure I like setting $LASTEXITCODE directly... probably better to let the system internals do it:

cmd /c "exit 0" #Reset $LASTEXITCODE between runs while debugging