How to evaluate powershell script inputed from std

2020-07-10 09:59发布

问题:

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

回答1:

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".