Exec() 总是会出现窗口闪烁。您可以改用Run() 在隐藏窗口中执行命令。但是您不能使用Run() 直接捕获命令的输出。您必须将输出重定向到一个临时文件,然后您的 VBScript 可以打开、读取和删除该文件。
例如:
With CreateObject("WScript.Shell")
' Pass 0 as the second parameter to hide the window...
.Run "cmd /c tasklist.exe > c:\out.txt", 0, True
End With
' Read the output and remove the file when done...
Dim strOutput
With CreateObject("Scripting.FileSystemObject")
strOutput = .OpenTextFile("c:\out.txt").ReadAll()
.DeleteFile "c:\out.txt"
End With
FileSystemObject 类具有诸如 GetSpecialFolder() 之类的方法来检索 Windows 临时文件夹的路径,并具有 GetTempName() 来生成可以使用的临时文件名,而不是像我在上面所做的那样对输出文件名进行硬编码。
还请注意,您可以将/FO CSV 参数与tasklist.exe 一起使用来创建一个CSV 文件,这将使解析变得更加容易。
最后,有 VBScript“本机”方法来检索正在运行的进程列表。例如,WMI 的 Win32_Process 类可以在不需要 Run/Exec 的情况下执行此操作。
编辑:
为了完整起见,我应该提到您的脚本可以在隐藏的控制台窗口中重新启动,您可以在其中静默运行Exec()。不幸的是,这个隐藏的控制台窗口也会隐藏你的输出,比如WScript.Echo()。但是,除此之外,您可能不会注意到在 cscript 与 wscript 下运行脚本的任何差异。下面是这个方法的一个例子:
' If running under wscript.exe, relaunch under cscript.exe in a hidden window...
If InStr(1, WScript.FullName, "wscript.exe", vbTextCompare) > 0 Then
With CreateObject("WScript.Shell")
WScript.Quit .Run("cscript.exe """ & WScript.ScriptFullName & """", 0, True)
End With
End If
' "Real" start of script. We can run Exec() hidden now...
Dim strOutput
strOutput = CreateObject("WScript.Shell").Exec("tasklist.exe").StdOut.ReadAll()
' Need to use MsgBox() since WScript.Echo() is sent to hidden console window...
MsgBox strOutput
当然,如果您的脚本需要命令行参数,那么在重新启动您的脚本时也需要转发这些参数。
编辑 2:
另一种可能性是使用 Windows 剪贴板。您可以将命令的输出通过管道传输到clip.exe 实用程序。然后,通过可访问剪贴板内容的任意数量的可用 COM 对象检索文本。例如:
' Using a hidden window, pipe the output of the command to the CLIP.EXE utility...
CreateObject("WScript.Shell").Run "cmd /c tasklist.exe | clip", 0, True
' Now read the clipboard text...
Dim strOutput
strOutput = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text")