84

Redirecting command output:

For example:

echo "Foo `./print_5_As.rb`"

would echo "Foo AAAAA"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

164

The PowerShell syntax is based on the POSIX ksh syntax (and interestingly not on any of Microsoft's languages like CMD.EXE, VBScript or Visual Basic for Applications), so many things work pretty much the same as in Bash. In your case, command substitution is done with

echo "Foo $(./print_5_As.rb)"

in both PowerShell and Bash.

Bash still supports the ancient way (backticks), but PowerShell cleaned up the syntax and removed redundant constructs such as the two different command substitution syntaxes. This frees up the backtick for a different use in PowerShell: in POSIX ksh, the backslash is used as escape character, but that would be very painful in PowerShell because the backslash is the traditional path component separator in Windows. So, PowerShell uses the (now unused) backtick for escaping.

Raúl Salinas-Monteagudo
  • 3,412
  • 1
  • 24
  • 22
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 27
    It's great reading answers like this where you get to learn how and why things are. Thanks! (I'd do +10 if I could.) – PEZ Jan 12 '09 at 15:13
29

In PowerShell, you use $( ) to evaluate subexpressions...

For example:

PS C:\> "Foo $(./print_5_As.rb)"
Foo AAAAA
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pete Richardson
  • 723
  • 6
  • 10
26

In CMD.EXE there is no direct equivalent. But you can use the FOR command to achieve what you want.

Do something like the following:

FOR /F "usebackq" %x IN (`./print_5_As.rb`) DO @echo Foo %x

or

FOR /F %x IN ('"./print_5_As.rb"') DO @echo Foo %x

You might need to set delimiter to something else than the default, depending on how the output looks and how you want to use it. More details available in the FOR documentation at https://technet.microsoft.com/en-us/library/bb490909.aspx

matli
  • 27,922
  • 6
  • 37
  • 37
  • 2
    Cumbersome, unlike it's uber-elegant bash equivalent: `for x in \`./print_5_As.rb\`; do echo %x; done` – jordanpg Apr 24 '15 at 15:14
  • 5
    @jordanpg, you seem to miss the point that FOR in this case is not used for looping. The bash equivalent would still be as in the original post, without any for loop. – matli Oct 29 '15 at 23:26
  • Only the first "word" of the output of print_5_As.rb is echoed if the output contains spaces. – Gnubie Jun 08 '17 at 14:20