【问题标题】:Calling Powershell with WshShell.Exec() method hangs the script使用 WshShell.Exec() 方法调用 Powershell 会挂起脚本
【发布时间】:2012-09-04 20:09:27
【问题描述】:

我正在尝试使用 WshShell 对象的 Exec 方法调用 Powershell。我正在用 JScript 编写脚本,但我也在 VBScript 中重现了这个问题。以下两个简短的测试脚本都会导致 WSH 无限期挂起:

test.js

var shell = new ActiveXObject("WScript.Shell");
WScript.Echo(shell.exec("powershell -Command $Host.Version; Exit").StdOut.ReadAll());

test.vbs

dim shell

set shell = CreateObject("WScript.Shell")
WScript.Echo shell.exec("powershell -Command $Host.Version; Exit").StdOut.ReadAll

是我做错了什么,还是遇到了限制/不兼容? Run 方法效果很好,但我需要捕获输出,这是它无法做到的。

编辑:我忘了提到我的平台是 Windows 7 Pro,64 位,带有 PowerShell 3。我也在带有 PowerShell 1 的 Windows XP 上进行了测试。

编辑 2:我更新了我正在运行的测试脚本以适应 x0n 的答案。不幸的是,我仍然有麻烦。这是我目前的测试:

test.js:

var shell = new ActiveXObject("WScript.Shell");
WScript.Echo(shell.exec('powershell -noninteractive -noprofile -Command "& { echo Hello_World ; Exit }"').StdOut.ReadAll());

test.vbs:

dim shell

set shell = CreateObject("WScript.Shell")
WScript.Echo shell.exec("powershell -noninteractive -noprofile -Command ""& { echo Hello_World ; Exit }""").StdOut.ReadAll

【问题讨论】:

    标签: powershell exec blocking wsh


    【解决方案1】:

    你必须关闭标准输入:

    var shell = new ActiveXObject("WScript.Shell");
    var exec = shell.Exec('powershell -noninteractive -noprofile -Command "& { echo Hello_World ; Exit }"');
    exec.StdIn.Close();
    WScript.Echo(exec.StdOut.ReadAll());
    

    Microsoft 说:

    StdIn is still open so PowerShell is waiting for input. (This is an
    "implementation consideration" that we're hoping to fix in V2. The
    PowerShell executable gathers all input before processing.) So
    objexec.StdIn.Close() needs to be added.
    

    【讨论】:

    • 您不必关闭 StdIn。但是您确实需要使用-NonInteractive-Command 参数才能成功。但是我对您的回答投了赞成票,因为关闭 StdIn 不会受到伤害,最终,我得到了这个工作。感谢发帖!!
    • 是否可以将它与 -File 选项结合使用,因为我必须运行一个巨大的脚本,而不仅仅是几行 ps1 命令?
    【解决方案2】:

    用途:

    powershell.exe -noninteractive -noprofile -command $host.version
    

    作为你的字符串。对于更复杂的命令组,请使用以下语法:

    powershell.exe -noninteractive -noprofile -command "& { $host.version; $host.version }"
    

    【讨论】:

    • 我尝试了您的建议,但不幸的是它没有解决问题。我在 wscript.exe 中运行它,我发现 powershell 窗口只是保持打开状态,但它完全是空白的。关闭此窗口允许 WSH 脚本继续执行。我在 Windows 7 和 XP 计算机上都对此进行了测试。
    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 2011-11-18
    • 2021-06-08
    相关资源
    最近更新 更多