1

How do I negate the exit code of an executable in powershell? I would like my script to succeed if an executable terminated with a non-zero exit code, or fail if the executable terminated with a zero exit code.

I tried the following ! (...) and it prints True, which sounds promising, however it also makes the script fail with exit code 1.

! (program.exe) # I want this line to fail if program.exe returns 0

Output:

True
Error: Process completed with exit code 1.

Note that I'm just interested in checking the exit code of the executable. If the executable fails for other reasons (e.g. missing libraries) then it's fine for the script to fail.

This question has some similarities to this question for -nix systems. However, I'm writing a powershell script to be run on Windows 10.

Federico
  • 1,925
  • 14
  • 19
  • include the full command please – marsze Oct 12 '20 at 16:07
  • @marsze The command that I want to run is an executable, and I'm looking for a solution that works for any kind of executable. – Federico Oct 12 '20 at 16:13
  • 2
    @Federico - since there is no way to predict what any given exe will do when it fails ... how on earth is one supposed to make a universal test? you MUST know what to look for ... and that is not always the same for any given application or utility. – Lee_Dailey Oct 12 '20 at 16:22
  • @Lee_Dailey You can do it on *nix platforms: https://stackoverflow.com/questions/367069/how-can-i-negate-the-return-value-of-a-process. I need the analogous, for powershell. – Federico Oct 12 '20 at 16:25
  • do you absolutely guarantee that all apps will always respond in the exact same way when they fail on a -nix system? [*frown*] that is absolutely false on windows systems. ///// **_if you want this for -nix systems, please add that tag & info to your Question._** – Lee_Dailey Oct 12 '20 at 16:28
  • @Lee_Dailey thanks for the feedback. In my case, I want to test that the return code of a program is non-zero, so if the executable fails for other reasons (e.g. missing libraries) it's fine for my script to fail. And no, I don't need to do this for -nix systems. I'm running a powershell script on Windows 10. – Federico Oct 12 '20 at 16:42
  • 1
    @Federico - try checking the `$LastExitCode` entry in the help file `about_Automatic_Variables`. i don't know if it works for the -nix stuff, tho. – Lee_Dailey Oct 12 '20 at 17:02
  • I might have the incorrect assumption that a powershell script ends as soon a non-zero exit code is reached. I'm now trying https://stackoverflow.com/a/47033834/2491528. – Federico Oct 12 '20 at 17:13
  • I'm not sure what you are aiming at? Would you like PowerShell to continue running (which it will until the end of the script) or would you just like PowerShell to detect the exit code left by another executable? – Dennis Aug 26 '21 at 21:09

0 Answers0