18

Does PowerShell have an equivalent to this command construct from sh (and derivatives):

$ cmd1 && cmd2

where cmd2 is only run when cmd1 exits sucessfully?

I know you can combine commands with a semicolon. However, this disregards the exit status of commands.

cxw
  • 16,089
  • 2
  • 40
  • 75
Luke Bakken
  • 7,262
  • 2
  • 15
  • 26

2 Answers2

9

Try this:

$errorActionPreference='Stop'; cmd1; cmd2
Ivan
  • 8,043
  • 4
  • 53
  • 69
  • 5
    If the first command fails with this approach, the next will still be executed. – Mathias Lykkegaard Lorenzen Mar 28 '15 at 13:19
  • Have just tested this -- the second command is still executed. – amn Sep 19 '18 at 14:13
  • Yes, sorry, I believe it should work only for native PowerShell cmdlets... – Ivan Sep 19 '18 at 14:30
  • I can barely understand the positive points. Your proposal would kill the full script, whereas "a && b" in a unix shell would not stop everything if A fails. – Raúl Salinas-Monteagudo Jun 27 '19 at 09:13
  • 1
    There is the "$?" automatic variable that stores if the command executed successfully. so cmd2 could be `if($?) { cmd2 }` I believe – Ty Deuty Feb 07 '20 at 16:08
  • It can work *if* commands throw an exception, thus breaking the processing chain. You can *usually* add `-ErrorAction Stop` to standard cmdlets so they throw an exception when failing, so further commands will not be executed. – Matthieu Mar 04 '20 at 14:20
6

There is no direct analog to && or ||. There are several discussions on alternatives though. Here is one example:

conditional execution (&& and ||) in powershell

Community
  • 1
  • 1
EBGreen
  • 35,429
  • 11
  • 62
  • 83
  • 1
    I realized the silliness of saying "here is the same question already answered" as I posted this answer. I've voted to close this question. – EBGreen Jun 19 '12 at 15:29
  • 2
    This page serves a purpose; when searching for "chain commands powershell" you get here. So you can follow your link to the real answer. – andersand Sep 09 '13 at 06:26