使用WshShell.Exec()方法调用Powershell会挂起脚本

时间:2012-09-04 20:09:27

标签: powershell exec blocking wsh

我试图用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专业版,64位使用PowerShell 3.我也在Windows XP上使用PowerShell 1测试过。

编辑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

2 个答案:

答案 0 :(得分:6)

你必须关闭StdIn:

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.

答案 1 :(得分:2)

使用:

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

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

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