I am trying to get the exit from the application running in a kubernetes cluster. I can see the pod status as Error but I am interested in getting the exact exit code.
Docker File:
# getting base image
FROM mcr.microsoft.com/windows/servercore:ltsc2019
# Copy powershell scripts
COPY scripts/ scripts/
# copy app
COPY app/ app/
# run script
ENTRYPOINT ["powershell", "C:\\scripts\\myscript.ps1"]
myscript.sp1:
# Run script 1
Invoke-Expression "& `"C:\\scripts\\myscript1.ps1`" "
# Run script 2
Invoke-Expression "& `"C:\\scripts\\myscript2.ps1`" "
#Invoke exe
Invoke-Expression "& `"C:\app\MyApp.exe`" "
# Write Exit Code
Write-Host $LASTEXITCODE
Write-Host "Exit with Exit Code"
exit $LASTEXITCODE
On error, I can see the pod status as 'Error' but I need to get the exact exit code returned from myscript.ps1. I can see the exit code when I look at the Pod's log but I don't see it in the container exit code.
I have also tried this How to start container with kubectl and get exit code back? without kubectl exec But getting status as true or false
kubectl run myjob4 -it --restart=Never --image=myacr.azurecr.io/myapp:v1 --restart=Never --overrides='"{\"apiVersion\":\"v1\",\"spec\":{\"nodeSelector\":{\"kubernetes.azure.com/os-sku\":\"Windows2019\",\"kubernetes.io/os\":\"windows\"}}}"'
Output:
10 Exit with Exit Code pod default/myjob5 terminated (Error)
$?
output:
False
Instead of false, how can I get the exit code of 10 ( in this case ) ?
Only the -File
parameter of the PowerShell CLI (powershell.exe
for Windows PowerShell, pwsh
for PowerShell (Core) 7+) passes a script file's exit code through as-is, and using -File
is the proper way to invoke a script file.
powershell.exe
defaults to the -Command
CLI parameter (whereas pwsh
defaults to -File
), and it only reports an abstract exit code by default, namely 0
if the last statement executed succeeded, and 1
otherwise. See this answer for details.Therefore, use the following in your Dockerfile:
# run script
ENTRYPOINT ["powershell", "-File", "C:\\scripts\\myscript.ps1"]
Two asides:
Invoke-Expression
(iex
) should generally be avoided; except in unusual circumstances, don't use it to invoke an external program or PowerShell script / command.
\
characters have no special meaning to PowerShell, so you never need to escape them as \\
(PowerShell's escape character is `
, the so-called backtick).
Therefore, use the following in your PowerShell script:
# Alternatively, simply:
# C:\scripts\myscript1.ps1
& "C:\scripts\myscript1.ps1"
# Run script 2
& "C:\scripts\myscript2.ps1"
#Invoke exe
& "C:\app\MyApp.exe"
# ...
exit $LASTEXITCODE