Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run multiple commands on success

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?

like image 406
kelloti Avatar asked Oct 05 '22 21:10

kelloti


1 Answers

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.

# 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

rm 'not-exists' -ea 1; ls

The -ErrorAction parameter is explained the help. Type Get-Help about_CommonParameters

like image 193
latkin Avatar answered Oct 13 '22 10:10

latkin