Which is the correct syntax to read back the ExitCode from a powershell script?

I am running on a windows PC a runner with the setting
**

shell = “powershell”
**

From gitlab CI/CD I call a powershell script this way:

> powershell -File ./script.ps1
> - echo $LASTEXITCODE
> - echo $?

Now the executing job gives following information:

ExitCode =
1
$ echo $LASTEXITCODE
0
$ echo $?
True
Cleaning up file based variables
Job succeeded

=> Here the script fails with the ExitCode=1 but the Job succeeded!!??

Question:
why I can not read the correct ExitCode with gitlab?

If I am not mistaken you are spawning a second powershell from your runners powershell. The script error occurs inside the second powershell, but the powershell itself dos not fail to execute. So from the main shell there is no visible error.
What you actually want to do is to just call

- ./script.ps1

instead of

- powershell -File ./script.ps1

Thanks for the answer - your explanation makes totally sense! After changing the .yml file call to:

  • ./script.ps1

I get following output:

ExitCode =
1
$ echo $LASTEXITCODE
1
$ echo $?
True
Cleaning up file based variables
Job succeeded

The return value of the powershell script is correct with:
“ExitCode = 1” and "$LASTEXITCODE = 1 "

But it still returns “Job succeeded” at the end. Do I need to read the return value in the .yml file in a different way? I thought if $LASTEXITCODE is not equal zero the job should always fail?!

I think I have seen some discussion that the runner actually looks for $? == False, but I don’t remember where and why it is not False in your case.
Reading the return value via echo is definitely not needed. It might even be the reason why the runner is happy afterwards since the echos do not fail.
Do you execute all those calls as single yml statements or in a condensed way?
If they are not single statements, the warning from here might apply:

I deleted all echo’s and the .yml file looks like this:

build-job: # This job runs in the build stage, which runs first.
script:
- echo “$CI_JOB_STAGE”
- ./script.ps1

the job sends:

ExitCode =
1
Cleaning up file based variables
Job succeeded

So it looks that the echo’s were not the problem in this case. If the runner looks for $?== False can I change the yml-file in such way that a return code > 0 from the powershell script sets the job to False? Maybe there is an example syntax for the yml-file…