48

In Windows' native CMD processor, you can use & to string commands together so that one runs immediately after the other. A && will run the second command only if the first completes without error.

This is different from piping commands together with | in that output from the first command is not sent to the second command, the commands are just simply run one after the other and output for each is sent to its usual place.

However, I get an error when I try to use & or && in PowerShell. Are there similar functions available in PowerShell, or is this feature being deprecated?

Iszi
  • 14,163

3 Answers3

58

The & operator in PowerShell is just the ; or Semicolon.

The && operator in PowerShell has to be run as an if statement.

Command ; if($?) {Command}

Example:

tsc ; if($?) {node dist/run.js}
SS4Soku
  • 596
  • 5
  • 2
1

Try this function, which can be used roughly the same way:

function aa() {
    if($?) {
        $command = [string]::join(' ', $args[1..99])
        & $args[0] $command
    }
}

Now && can be replaced with ; aa, which while still not perfect is a lot more succinct.

cls && build

becomes

cls; aa build
mopsled
  • 931
0

Update: It is now possible to do it natively with Powershell 7

Write-Output 'First' && Write-Output 'Second'

First
Second

But if the first command fails (here note the Write-Error):

Write-Error 'Bad' && Write-Output 'Second'

Bad

Source : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipeline_chain_operators?view=powershell-7.3