为cmd传递多个命令以作为一个块

时间:2015-08-30 12:22:27

标签: vbscript

我为锻炼目的创建了一个非常简单的脚本。我只是尝试输出命令myshell.run "tasklist | find 'cmd.exe'"的结果。但它失败并显示错误消息。错误信息是德语'Anweisungsende erwartet',用英语表示'语句完成预期'

set myshell = CreateObject("WScript.Shell")

myvar = ""
myvar = myshell.run "tasklist | find 'cmd.exe'"


MsgBox "Output = " & myvar

我希望输出像这样: cmd.exe 5076 Console 1 3.156 K

更新

我再次尝试了可能重复链接的信息。 我必须使用Exec而不是Run

Set objShell = WScript.CreateObject("WScript.Shell")
Set objExecObject = objShell.Exec("cmd /C tasklist | find 'cmd.exe'")
strText = ""

Do While Not objExecObject.StdOut.AtEndOfStream
    strText = strText & objExecObject.StdOut.ReadLine()
Loop

Wscript.Echo strText

结果:即使cmd.exe正在运行,也没有输出。我认为如果有管道符号就不可能执行它。如果我只使用cmd /C tasklist,那么它会输出所有任务。

1 个答案:

答案 0 :(得分:1)

如果要将cmd的多个命令传递为一个块,则需要在它们周围加上引号。
您还必须尊重必须用于CMD的quote escaping rules,因为您的其中一个阻止命令find也使用了引号。
最后,您必须记住根据语言规则(VBScript)转义生成的CMD转义引号。

最后你应该:

Set objShell = WScript.CreateObject("WScript.Shell")
Set objExecObject = objShell.Exec("cmd /C ""tasklist | find ^""cmd.exe^""""")
strText = ""

Do Until objExecObject.StdOut.AtEndOfStream
    strText = strText & objExecObject.StdOut.ReadLine()
Loop

Wscript.Echo strText

作为调试提示,如果您未从StdOut获得结果,则还应以相同方式检查StdErr

相关问题