0
votes

I have a situation where a compiled app calls cmd.exe which runs a batch file that calls

powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command “& {.\script.ps1}

script.ps1 has the line $host.setshouldexit($exitcode).

But for some reason the powershell.exe process executing the PS1 doesn’t exit. Even if I run

powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command “& {.\script.ps1;Exit $lastexitcode} 

it never gets past the PS1 to the Exit command. Adding Exit to the end of the PS1 doesn't work either. The real annoyance is that all of this works just fine if I manually fire up CMD, open another CMD to replicate the compiled app doing it, and execute the batch file that calls powershell.exe.

2
Is your app calling cmd.exe /c or cmd.exe /k? Also you could just call exit $exitcode. - Bacon Bits
You are missing trailling quotes in your samples. Is that just a copy paste error? Also I see smart quotes. Use regular quotes in your real codes. Those can sometimes cause issues > " - Matt
@Matt The end quotes are missing. - arkiados
@BaconBits looked at the app source code today. It is C++ and calling the batch file with cmd.exe /c. I could call exit $exitcode but it isn't always accurate. $host.setshouldexit($exitcode) gives us consistent results and works everywhere else. It just isn't working when called using cmd /c by the app. - arkiados
To give an example of why to use SetShouldExit, I have a ps1 script that simply calls $host.SetShouldExit(1234). Watch what happens when I use Exit $LASTEXITCODE. ----- cmd /c test.cmd powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "& {".\Test.ps1";Exit $LASTEXITCODE}" echo errorlevel: 0 ----- cmd /c test.cmd powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "& {".\Test.ps1"}" echo errorlevel: 1234 - arkiados

2 Answers

0
votes

Well, the is an error with the post you made. The missing closing 'Double Quote', but I am sure that was a copy paste thing.

Yet, try changing your posted commands to this:

powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process powershell .\script.ps1}"

powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command “& {Start-Process .\script.ps1;Exit $lastexitcode}" 

Even without this...

$host.setshouldexit()

...they should auto close.

0
votes

Check your working directory

powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command “& {pwd;.\script.ps1}"

seems like the working directory is wrong and is important as you are using relative path.

else give the absolute path to the script.