如何评估从stdin输入的Powershell脚本

san*_*ige 6 powershell stdin

我想评估Powershell中StdIn的内容,如下所示:

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

输出: echo 12;

不幸的是,$input它不是String,而是a System.Management.Automation.Internal.ObjectReader,它iex无法按预期方式工作...因为此代码正常工作:

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

输出: 12

Mar*_*cus 6

以下将起作用:

使用脚本块:

echo "echo 12;" | powershell -noprofile -noninteractive -command { $input | iex }
Run Code Online (Sandbox Code Playgroud)

或使用单引号避免字符串插值:

 echo "echo 12;" | powershell -noprofile -noninteractive -command '$input | iex'
Run Code Online (Sandbox Code Playgroud)

因此$ input变量不会扩展,字符串'$ input'会传递给iex。

这两个都给我“ 12”。