1

I noticed that if I use Write-Error and after that exit 123 the $lastexitcode variable is not changed, instead it still contains the exit code from the previous command.

Given I have these files:

test-out.ps1:

Write-Output "hello"
exit 3

test-err.ps1

Write-Error "hello"
exit 123

Then I call in a powershell:

.\test-out.ps1
// displays: hello
$lastexitcode
// displays: 3

.\test-err.ps1
// displays: Write-Error: hello
$lastexitcode
// also/still displays: 3

I expected $lastexitcode after .\test-err.ps1 to be 123.

My workaround is to use [Console]::Error.WriteLine("hello"), but it seems like Write-Error should be the preferred way of doing this.

The documentation says

To write a non-terminating error, enter an error message string, an ErrorRecord object, or an Exception object. Use the other parameters of Write-Error to populate the error record.

It doesn't mention that it will prevent setting a custom exit code. And worse, using this doesn't set an exit code at all. If it was 0 before, then after using Write-Error and then exit 1 won't even work.

Am I missing something?

3
  • 2
    Cannot reproduce. Dou you have a line $ErrorActionPreference = 'Stop' in your script? In this case Write-Error produces a script-terminating error, so the exit 123 line won't be executed. Try Write-Error "hello" -EA Continue to ensure it doesn't terminate the script. Commented Aug 13, 2022 at 13:08
  • Thanks! Yes, I indeed had $ErrorActionPreference = 'Stop' from a previous test or script still set. 🙈 Commented Aug 13, 2022 at 13:14
  • 1
    Albeit a proof was missing, the indices were obvious for investigator @mklement0 and his assistant zett42. After the confession of the main suspect, the case could finally be closed. 🕵️ Commented Aug 13, 2022 at 14:27

1 Answer 1

3

Your symptom implies:

  • that your exit 123 statement was never executed

  • which in turn means that Write-Error, which by default emits a non-terminating error, happened to emit a script-terminating error,

  • which in turn implies that the $ErrorActionPreference = 'Stop' was in effect.

Sign up to request clarification or add additional context in comments.

2 Comments

I actually do have that in place (from a previous script call, I think, or maybe from testing things out). In a fresh Powershell my example does not work and the correct exitcode is set, Thanks!
Glad to hear it, @para.

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.