Question:
In bash & CMD you can do rm not-exists && ls
to string together multiple commands, each running conditionally only if the previous commands succeeded.
In powershell you can do rm not-exists; ls
, but the ls
will always run, even when rm
fails.
How do I easily replicate the functionality (in one line) that bash & CMD do?
Answer:
Most errors in Powershell are “Non-terminating” by default, that is, they do not cause your script to cease execution when they are encountered. That’s why ls
will be executed even after an error in the rm
command.
You can change this behavior in a couple of ways, though. You can change it globally via the $errorActionPreference
variable (e.g. $errorActionPreference = 'Stop'
), or change it only for a particular command by setting the -ErrorAction
parameter, which is common to all cmdlets. This is the approach that makes the most sense for you.
1 2 3 4 |
# setting ErrorAction to Stop will cause all errors to be "Terminating" # i.e. execution will halt if an error is encountered rm 'not-exists' -ErrorAction Stop; ls |
Or, using some common shorthand
1 2 |
rm 'not-exists' -ea 1; ls |
The -ErrorAction
parameter is explained the help. Type Get-Help about_CommonParameters