[英]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.