Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: $LASTEXITCODE in a function

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

like image 303
blue18hutthutt Avatar asked Jun 08 '12 05:06

blue18hutthutt


People also ask

How do I use $Lastexitcode in PowerShell?

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.

How do I get the return value of a PowerShell script?

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...

What is $? In PowerShell?

$? 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.

How do I echo in PowerShell?

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.


2 Answers

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

like image 106
manojlds Avatar answered Sep 22 '22 13:09

manojlds


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.

like image 44
Senfbrot Avatar answered Sep 21 '22 13:09

Senfbrot