Powershell: $LASTEXITCODE in a function

14,646

Solution 1

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

Solution 2

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.

Solution 3

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
Share:
14,646
blue18hutthutt
Author by

blue18hutthutt

Just your average .NET developer

Updated on July 06, 2022

Comments

  • blue18hutthutt
    blue18hutthutt almost 2 years

    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