[英]how to run multiple commands on success
在bash和CMD中,你可以使用rm not-exists && ls
将多个命令串在一起,每个命令只有在前面的命令成功时才有条件地运行。
在powershell中,你可以做到rm not-exists; ls
rm not-exists; ls
,但即使rm
失败, ls
也会一直运行。
如何轻松复制bash和CMD的功能(在一行中)?
Powershell中的大多数错误默认为“非终止”,也就是说,它们不会导致脚本在遇到脚本时停止执行。 这就是为什么即使在rm
命令出错之后也会执行ls
。
但是,您可以通过几种方式更改此行为。 您可以通过$errorActionPreference
变量全局更改它(例如$errorActionPreference = 'Stop'
),或者通过设置-ErrorAction
参数仅对特定命令进行-ErrorAction
,这对所有cmdlet都是通用的。 这是最适合您的方法。
# 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
或者,使用一些常见的速记
rm 'not-exists' -ea 1; ls
-ErrorAction
参数解释了帮助。 键入Get-Help about_CommonParameters
要检查powershell命令的退出代码,您可以使用$?
。
例如,以下命令将尝试删除not-exists
,如果成功则将运行ls
。
rm not-exists; if($?){ ls }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.