Bash / Batch-like subshell in Powershell

In a Unix shell, you can write this:

( cmd1 ; cmd2 ) | cmd3

      

In Windows Batch, you can write this

( cmd1 & cmd2 ) | cmd3

      

In both cases, the output of cmd1 and cmd2 is piped to cmd3 on stdin.

Can you do the same in Powershell?

I have not found a valid syntax that allows this. I would have expected an expression block to work like this, but it doesn't:

{ cmd1 ; cmd2 ) | cmd3

      

I can make it work by declaring a function:

function f() {
    cmd1
    cmd2
}
f | cmd3

      

Is there a syntax to do this online?

+3


source to share


1 answer


I think this works:

Invoke-Command {cmd1; cmd2} | cmd3

      



In the documentation :

The Invoke-Command cmdlet runs commands on the local or remote computer and returns all command output, including errors.

...

You can also use Invoke-Command on your local machine to evaluate or run a line in a script block as a command. Windows PowerShell converts a script block to a command and immediately runs the command in the current scope, rather than just echoing a line on the command line.

0


source







All Articles