0

To execute multiple commands in PowerShell we use ; . But there is a flaw in it it executes all the commands even if one fails in between.

Is there any substitute for && in Windows Powershell ?

piyush172
  • 80
  • 9
  • Does this answer your question? [What are the PowerShell equivalents of Bash's && and || operators?](https://stackoverflow.com/questions/2416662/what-are-the-powershell-equivalents-of-bashs-and-operators) – Omkar76 Sep 18 '20 at 15:04

1 Answers1

1

But there is a flaw in it it executes all the commands even if one fails in between.

Try setting the appropriate preference variable - it defaults to Continue in powershell.exe:

$ErrorActionPreference = 'Stop'

Some-Command
Some-CommandThatMightFail
Some-OtherCommand

Now, if Some-CommandThatMightFail throws an error, execution of the containing script or function will stop and return to the caller immediately.

See the about_Preference_Variables topic in the documentation on more information about controlling error handling behavior with $ErrorActionPreference


Beware that the $ErrorActionPreference = 'Stop' assignment only affects the current scope - overwriting it will only affect the error action preference in the script/function/scriptblock where that assignment was executed:

PS C:\> $ErrorActionPreference
Continue
PS C:\> &{ 
  $ErrorActionPreference = 'Stop'
  # preference only changes inside this scriptblock
  $ErrorActionPreference
}
Stop
PS C:\> $ErrorActionPreference # still Continue in parent scope
Continue
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206