Powershell: $LASTEXITCODE in a function
Asked Answered
G

4

18

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

Gherkin answered 8/6, 2012 at 5:36 Comment(0)
R
31

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

Rotate answered 8/6, 2012 at 6:16 Comment(0)
D
5

To extend on what has been written already:

The $LASTEXITCODE variable lives - is set by powershell - in global scope.

That is why, when you're in the terminal, setting $lastexitcode = 0, before calling something, works totally fine. In the terminal the global scope is the local scope is the script scope.

However, as soon as you are in an actual script or in a function, setting unqualified $LASTEXITCODE will create a local/script scope variable of that name that will "shadow" the global one.

So the rule, if you will, is:

  • NEVER set $LASTEXITCODE = ... outside ad hoc work on the terminal
  • ALWAYS use $global:LASTEXITCODE = ... to reset it.
  • PREFER reading via ... = $global:LASTEXITCODE to prevent accidentally reading a "shadowed" version of this variable
  • No immediate need to refactor scripts and functions that read via $LASTEXITCODE though.
Deserved answered 23/12, 2022 at 7:27 Comment(0)
G
4

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.

Gray answered 8/6, 2012 at 15:23 Comment(0)
B
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
Barge answered 8/9, 2016 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.