How to run multiple success teams

In bash and CMD, you can do rm not-exists && ls to combine several commands, each of which is executed conditionally only if the previous commands were successful.

In powershell you can do rm not-exists; ls rm not-exists; ls , but ls will always work, even if rm does not work.

How easy is it to replicate the functionality (in one line) that bash and CMD do?

+4
source share
2 answers

Most errors in Powershell are "Non-terminating" by default, that is, they do not cause your script to stop executing when they occur. Therefore, ls will be executed even after an error in the rm command.

However, you can change this behavior in several ways. You can change it globally using the $errorActionPreference variable (for example, $errorActionPreference = 'Stop' ) or change it only for a specific command by setting the -ErrorAction parameter, which is common to all cmdlets. This is the approach that makes the most sense to you.

 # setting ErrorAction to Stop will cause all errors to be "Terminating" # ie execution will halt if an error is encountered rm 'not-exists' -ErrorAction Stop; ls 

Or using some common abbreviations

 rm 'not-exists' -ea 1; ls 

The -ErrorAction parameter -ErrorAction explained by help. Type Get-Help about_CommonParameters

+4
source

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

For example, the following command will try to remove not-exists , and if it succeeds, it will start ls .

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

All Articles