47

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
  • 13,775

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
  • 1
    Can this be chained? And does failure still send a non-zero exit message? – aaronsteers Dec 16 '20 at 18:52
  • 1
    Since PowerShell Core v7, && and || can be used directly. – brc-dd Dec 31 '20 at 14:28
  • This does not seem to work - if(git add -A) { if(git commit -a -m "comment") {git push}} whereas in unix this works as git add -A && git commit -a -m "comment" && git push. – lonstar Jul 01 '23 at 11:30
  • @aaronsteers ; if($?) can be chained. For example, [command1] ; if($?) { [command2] } ; if($?) { [command3] } – Mykel Jan 03 '24 at 19:13
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
  • 851
  • 1
    Any non-stylistic reason why you're using args[0] and not function aa ($cmd)? – ruffin Nov 25 '14 at 15:23
  • This is a brittle way to invoke commands; use script blocks to pass commands around, and invoke those with ., not &, because the latter creates a child scope for variables. – mklement0 Jan 23 '17 at 22:00
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