1

I am trying to get a return code from a Powershell cmdlet. This return code will be passed to a Saltstack cmd.run state (success_retcodes parameter)

My cmdlet that should produce an error:Get-PSSessionConfiguration test

This will produce an error because test session does not exist. Running $? right after always produces True whether the above cmdlet fails or not.

The purpose of this exercise is purposely not fail one of my states in Saltstack via the aforementioned parameter which I believe takes a numeral value. Any suggestions would be appreciated.

2 Answers 2

2

Why not just use the good ol' try/catch block?

Try {
    Get-PSSessionConfiguration test -ErrorAction stop
    return $true
} Catch {
    return $false
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Sebastian. I am trying to get the raw error code without changing it to something else
If you want just the error then you can either throw the error or write it as output - 'throw $_' or '$_' - in case you would like to process the error first, grab the error type for example you could either do it within the catch block - or just assign the error into a variable and then process it from there. ``` [...] catch { throw $_ } ``` or ``` $errorvar = $_ ``` And then process the errorvar to your liking, or just leave the '$errorvar=' out - leaving you with just the whole text of error output.
1

$LASTEXITCODE returns the last exit code. Or, $Error is where all errors are stored. From there you can filter what error you'd like to catch.

$Error | Select Exception

1 Comment

Thanks for this. $Error provides with the actual error messages as opposed to an error code right? I tried to dig the entries and couldn't find what I need. As far as I ca recall $lastexitcode only capture error codes from external command, not Powershell cmdlets. That is why I was quick to check the $? global variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.