Executing Commands in Groups

by May 15, 2012

In traditional batch files, you can use "&&" to execute a second command only if the first one worked. In PowerShell, the same can be achieved by using the try/catch construct. You just need to know some little tricks. Take a look at this:

try {
  $ErrorActionPreference='Stop'
  # commands follow
}
catch {}

Now, if you want to execute a group of command and abort everything once an error occurs, simply place the commands inside the try block. If the commands are native console commands, add a "2>&1" to each command.

try {
  $ErrorActionPreference='Stop'
  net user nonexistent 2>&1   # this raises an error
  ipconfig 2>&1               # this will not execute due to the previous error
}
catch {}

Try and replace "nonexistent " with an existing local user account such as "Administrator", and you'll see that ipconfig will execute.

Twitter This Tip! ReTweet this Tip!