Fabian
Fabian

Reputation: 5650

Run command in powershell and ignore exit code in one line

I try to execute a command in powershell and ignore any non zeroexit code. Unfortunately I completely fail doing this :-(

Under Linux this is done with this trivial line:

command arg1 arg2 || echo "ignore failure"

The or clause is executed only in case of a failure and then the exit code of echo resets $?

I thought something like this would do the trick:

Invoke-Expression "command arg1 arg2" -ErrorAction Ignore

But $LASTEXITCODE is still set to a non zero value

Upvotes: 2

Views: 3923

Answers (1)

mklement0
mklement0

Reputation: 440317

PowerShell v7+'s pipeline-chain operators, && and ||, implicitly act on $LASTEXITCODE, but never reset it.

If you do want to reset it - which is generally not necessary - you can do the following:

command arg1 arg2 || & { "ignore failure"; $global:LASTEXITCODE = 0 }

Note that PowerShell scripts - unlike scripts for POSIX-compatible shells such as bash - do not implicitly exit with the exit code of the most recently executed command; instead, you must use exit $n explicitly, where $n is the desired exit code.

In the context of calling the PowerShell CLI from the outside, the above applies to using the -File parameter to call a script; for use with the -Command (-c) parameter, see the next section.


As for what you tried:

  • || and && don't work in Windows PowerShell (versions up to v5.1) at all.

  • Invoke-Expression doesn't help here and should generally be avoided and used only as a last resort, due to its inherent security risks. In short: Avoid it, if possible, given that superior alternatives are usually available. If there truly is no alternative, only ever use it on input you either provided yourself or fully trust - see this answer.

If you're using the Windows PowerShell CLI with -Command (-c), and you need to make sure that the PowerShell process exits with exit code 0, do something like the following (... represents your command):

powershell.exe -noprofile -c "...; exit 0"

If you want to comment on the failure:

powershell.exe -noprofile -c "...; if ($LASTEXITCODE) { 'ignore failure' }; exit 0"

Note: In this case, ; exit 0 isn't strictly necessary, because the if statement alone, due to it succeeding, irrespective of the value of $LASTEXITCODE, is enough to make the exit code 0.
Also, note that PowerShell CLI sends all of PowerShell's output streams - including the error stream - to stdout by default, though you can selective redirect the error stream on demand with 2>.

This also applies to the PowerShell [Core] v7+ CLI, whose executable name is pwsh, and whose parameters are a superset of the Windows PowerShell CLI.

For more information on PowerShell with respect to process exit codes, see this answer.

Upvotes: 2

Related Questions