9

I want to evaluate the content from StdIn in PowerShell, like this:

echo "echo 12;" | powershell -noprofile -noninteractive -command "$input | iex"

Output:

echo 12;

Unfortunately, $input is not a String, but a System.Management.Automation.Internal.ObjectReader, which make iex not working as expected... since this one is working correctly:

powershell -noprofile -noninteractive -command "$command = \"echo 12;\"; $command | iex"

Output:

12
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
sandvige
  • 168
  • 2
  • 6

2 Answers2

5

The following would work:

Use a scriptblock:

echo "echo 12;" | powershell -noprofile -noninteractive -command { $input | iex }

Or use single quotes to avoid the string interpolation:

 echo "echo 12;" | powershell -noprofile -noninteractive -command '$input | iex'

so the $input variable isn't expanded, and the string '$input' is passed to iex.

Both of these give me "12".

Marcus
  • 5,987
  • 3
  • 27
  • 40
  • This is working when you're running this from another PowerShell, but it's not working when using it from cmd.exe. Why? – sandvige Dec 14 '12 at 13:13
  • 1
    That's to do with the quotes around the "echo 12;". If you execute this in powershell echo "echo 12;" gives echo 12; without the quotes. In cmd.exe you'll see that it writes "echo 12;", which is then interpreted as a string by Powershell. To make it work in cmd.exe you can try: `echo echo 12; | powershell -noprofile -noninteractive -command "$input | iex"` – Marcus Dec 14 '12 at 14:18
3

Just use - as a source file "name":

echo "echo 12;" | powershell -noprofile -noninteractive -
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992