kelloti
kelloti

Reputation: 8951

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?

Upvotes: 5

Views: 2172

Answers (2)

Brett
Brett

Reputation: 2823

To check the exit code from a powershell command you can use $?.

For example, the following command will try to remove not-exists and if it is successful it will run ls.

rm not-exists; if($?){ ls }

Upvotes: 1

latkin
latkin

Reputation: 16792

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

Upvotes: 5

Related Questions