简体   繁体   English

如何在成功时运行多个命令

[英]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. 在bash和CMD中,你可以使用rm not-exists && ls将多个命令串在一起,每个命令只有在前面的命令成功时才有条件地运行。

In powershell you can do rm not-exists; ls 在powershell中,你可以做到rm not-exists; ls rm not-exists; ls , but the ls will always run, even when rm fails. rm not-exists; ls ,但即使rm失败, ls也会一直运行。

How do I easily replicate the functionality (in one line) that bash & CMD do? 如何轻松复制bash和CMD的功能(在一行中)?

Most errors in Powershell are "Non-terminating" by default, that is, they do not cause your script to cease execution when they are encountered. Powershell中的大多数错误默认为“非终止”,也就是说,它们不会导致脚本在遇到脚本时停止执行。 That's why ls will be executed even after an error in the rm command. 这就是为什么即使在rm命令出错之后也会执行ls

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. 您可以通过$errorActionPreference变量全局更改它(例如$errorActionPreference = 'Stop' ),或者通过设置-ErrorAction参数仅对特定命令进行-ErrorAction ,这对所有cmdlet都是通用的。 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. -ErrorAction参数解释了帮助。 Type Get-Help about_CommonParameters 键入Get-Help about_CommonParameters

To check the exit code from a powershell command you can use $? 要检查powershell命令的退出代码,您可以使用$? .

For example, the following command will try to remove not-exists and if it is successful it will run ls . 例如,以下命令将尝试删除not-exists ,如果成功则将运行ls

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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