Powershell: $LASTEXITCODE in a function

blue18hutthutt picture blue18hutthutt · Jun 8, 2012 · Viewed 13.9k times · Source

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

Answer

manojlds picture manojlds · Jun 8, 2012

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