gpt4 book ai didi

vbscript - 使用 Exec() 时隐藏命令提示符窗口

转载 作者:行者123 更新时间:2023-12-03 22:49:06 25 4
gpt4 key购买 nike

我正在尝试执行这个简单的测试脚本,但是在我执行脚本后会出现一个命令外壳窗口。:

Set objShell = WScript.CreateObject("WScript.Shell")

strCommand = "cmd /C tasklist"

Set objExecObject = objShell.Exec(strCommand)

wscript.echo "Test"

我怎样才能防止它出现?

更新

我能够通过此代码更改对其进行改进:
strCommand = "cmd /C /Q tasklist"

现在窗口只显示一瞬间。但我根本不希望它出现。

最佳答案

你总是会用 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 CSVtasklist.exe 的论点创建一个 CSV 文件,它应该使解析更容易。

最后,还有 VBScript 的“ native ”方法来检索正在运行的进程列表。 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")

关于vbscript - 使用 Exec() 时隐藏命令提示符窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32297699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com