如何在 PowerShell 会话中访问 powershell.exe 命令的结果



我正在尝试使用此命令从CMD启动PowerShell。

powershell.exe -NoProfile -NoExit -command "& {$someVar = 'test'}"

如何在PowerShell中访问变量someVar。MSDN 表示"脚本的结果作为反序列化的 XML 对象返回到父外壳,而不是活动对象。

>& {$someVar = 'test'}"在本地范围内执行脚本块,当它完成脚本块执行时,该脚本块将被删除。

您需要在$global范围(会话范围(中创建变量

CMD> powershell.exe -NoProfile -NoExit -command "& {$global:someVar = 'test'}"
PS> $someVar
test

或者使用点源. <script/scriptblock>来执行脚本块,该脚本块运行当前范围内的所有内容(在本例中为会话(

CMD> powershell.exe -NoProfile -NoExit -command ". {$someVar = 'test'}"
PS> $someVar
test

在此处阅读有关变量作用域的更多信息

最新更新