简体   繁体   中英

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 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?

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 (eg $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

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM