在VBScript中,内置Shell.Run
方法不提供输出重定向,因此必须使用以下解决方法:
Running command line silently with VbScript and getting output?
Dim retVal
retVal = WshShell.Run( "cmd /c ""commandGoesHere"" > c:\temp\output.txt", 0, True )
但是returnValue
的返回值为cmd
,而不是commandGoesHere
。
我以为我可以查看shell.Environment("ERRORLEVEL")
,但可能这也是cmd
的返回值,而不是commandGoesHere
。
...那么如何让commandGoesHere
的返回值和同时将其输出重定向到另一个文件?
答案 0 :(得分:3)
returnValue = WScript.CreateObject("WScript.Shell").Run( _
"cmd /v /c (>""output.txt"" ""commandGoesHere"" & exit !errorlevel!)" _
, 0 _
, True _
)
启用已启用延迟扩展的cmd
实例(/v
)并退出cmd
实例,并使用上一个命令设置的errorlevel
。
需要延迟扩展,因为cmd
解析器在行/块解析阶段使用变量内的值替换所有%var%
读取操作。如果没有延迟扩展(%errorlevel%
),将在开始执行命令之前重新执行exit
命令返回的值。对于延迟扩展(!errorlevel!
),在exit
结束后执行commandGoesHere
命令时将检索该值。