How-to: Run multiple commands in one line in Powershell

How to execute multiple commands in one line with Powershell.

Table of Contents

There are several good reasons to run multiple commands in a single line.

For example, if you are on Teamviewer and want to ipconfig /release and ipconfig /renew. You would be screwed if you tried to do the two commands in two lines.

Method 1

Syntax: command1; command2

The commands are being run sequentially.
Meaning it runs and finishes the first command, then the next and so on.


If one of the commands fails, it will throw an error message and continue to the next command.

Method 2

Syntax: Try {command1 -ErrorAction Stop} Catch {Command-Two}

Only if the first command fails, will it will run the second command.

It’s basically method 4, but here you don’t need Powershell 7.

Method 3

Syntax: command1 && command2

This syntax will only run the second command if the first succeeds.

This requires Powershell 7!
Use $PSVersiontable to check your version.

Method 4

Syntax: command1 || command2

This syntax will only run the second command if the first one fails.

This requires Powershell 7!
Use $PSVersiontable to check your version.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *