25

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?

35

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

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

Command ; if($?) {Command}

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
  • 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

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.