Home > front end >  How can I ensure a line of PowerShell does not break the script on failure?
How can I ensure a line of PowerShell does not break the script on failure?

Time:12-13

I have a command mycommand that sometimes gives a bad exit code, but I want to continue executing the script. However, I don't want to disable exiting on bad exit codes for the other lines.

On Linux systems I can change the command to mycommand || true which will ensure that this line always succeeds. How can I do this on Windows in PowerShell? If I try || true as-is, PowerShell says "The token '||' is not a valid statement separator in this version". What's the equivalent in PowerShell?

CodePudding user response:

For any given command, irrespective of its form, the following idiom ensures that:

  • (a) execution isn't aborted and
  • (b) no error is reported.
try {
  & $someCommand 2>$null
} catch { }
  • Redirection 2>$null discards non-terminating errors as well as stderr output from external programs (which by default do not affect the execution flow).

  • try / catch captures all terminating errors (both statement- and script-terminating errors), and by leaving the catch block blank, execution resumes quietly.

Note:

  • For a systematic overview of PowerShell's bewilderingly complex error handling, see GitHub docs issue #1583

  • || and && are available in PowerShell (Core) 7 - see this answer - however:

    • they do not act on script-terminating errors
    • they do not themselves silence errors, and silencing statement-terminating errors isn't possible with || and && (unless you set $ErrorActionPreference = 'SilentlyContinue' first; otherwise, you need try / catch, which cannot be meaningfully combined with || and &&).

CodePudding user response:

The solution is to use the -ErrorAction SilentlyContinue common parameter. However, note that this only applies to Cmdlets, not all commands. If you want to run a non-Cmdlet command, you need to wrap it in a Cmdlet:

Invoke-Expression -ErrorAction SilentlyContinue -Command "mycommand"

CodePudding user response:

Try catch block with ErrorAction stop for regular cmdlets should work great

try {
    remove-item "C:\nonexistentfile" -ErrorAction Stop
}
catch {
    Write-Host $_
}

CodePudding user response:

Powershell 7 has that operator.

dir foo || $true

Get-ChildItem: Cannot find path 'C:\Users\js2010\foo\foo' because it does not exist.
True
  • Related