2014-02-28 53 views
4

这是我到目前为止。有用;将文件夹路径输出到一个文本文件。 我真正想要的是将数据输出到一个变量。每一个例子,我在网上看到,展示了如何做到这一点使用是这样的:VBS将cmd.exe输出运行到变量;而不是文本文件

set objScriptExec = wshShell.Exec (strCommand) 

其次

strresult = LCase(objScriptExec.StdOut.ReadAll. // code 

我想这与Run,不Exec跑,因为我要在命令提示符窗口被隐藏,因为我将用下面的代码执行许多命令。我怎样才能捕捉到一个变量的输出?

Set wsShell = CreateObject("WScript.Shell") 
strCommand = "cmd /c echo %temp% > %temp%\test.txt" 
wsShell.Run strcommand,0,True 
+0

我相信你已经看过这个,但为什么不把它存储在一个文本文件中,读取文本文件,然后删除它? http://stackoverflow.com/questions/5690134/running-command-line-silently-with-vbscript-and-getting-output – Rich

+0

或http://stackoverflow.com/a/4963209/603855 –

回答

1

当然Wscript.Shell会轻松很多,但是,因为你希望你的会议更细粒度的控制,可以考虑使用Win32_Process。通常,使用这个来控制一个新窗口的位置,但在你的情况下,你想隐藏它,所以我设置了startupInfo.ShowWindow = 0这意味着SW_HIDE。以下声明一个名为RunCmd的函数VBScript,它将在不可见的窗口中运行一个命令,将输出保存到文本文件中,然后将文本文件的内容返回给调用者。举个例子,我调用RunCmdHOSTNAME命令:

Function RunCmd(strCmd) 
    Dim wmiService 
    Set wmiService = GetObject("winmgmts:\\.\root\cimv2") 
    Dim startupInfo 
    Set startupInfo = wmiService.Get("Win32_ProcessStartup") 
    Dim fso 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Dim cwd 
    cwd = fso.GetAbsolutePathname(".") 
    startupInfo.SpawnInstance_ 
    startupInfo.ShowWindow = 0 
    ' startupInfo.X = 50 
    ' startupInfo.y = 50 
    ' startupInfo.XSize = 150 
    ' startupInfo.YSize = 50 
    ' startupInfo.Title = "Hello" 
    ' startupInfo.XCountChars = 36 
    ' startupInfo.YCountChars = 1 
    Dim objNewProcess 
    Set objNewProcess = wmiService.Get("Win32_Process") 
    Dim intPID 
    Dim errRtn 
    errRtn = objNewProcess.Create("cmd.exe /c """ & strCmd & """ > out.txt", cwd, startupInfo, intPID) 
    Dim f 
    Set f = fso.OpenTextFile("out.txt", 1) 
    RunCmd = f.ReadAll 
    f.Close 
End Function 

MsgBox RunCmd("HOSTNAME") 

参考文献:

+0

我想保持清晰从制作txt文件。会想到会有一种方法输出到变量而不是txt文件。 – user3366722

2

这可能与Windows脚本来完成主机exec命令。 StdOut,StdIn和StdErr都可以访问,并且命令完成时ERRORLEVEL可用。

Dim strMessage, strScript, strStdErr, strStdOut 
Dim oExec, oWshShell, intErrorLevel 
Dim ComSpec 

Set oWshShell = CreateObject("WScript.Shell") 
ComSpec = oWshShell.ExpandEnvironmentStrings("%comspec%") 

intErrorLevel = 0 
strScript = ComSpec & " /C echo %temp%" 

On Error Resume Next 
Set oExec = oWshShell.Exec (strScript) 
If (Err.Number <> 0) Then 
    strMessage = "Error: " & Err.Message 
    intErrorLevel = 1 
Else 
    Do While oExec.Status = 0 
    Do While Not oExec.StdOut.AtEndOfStream 
     strStdOut = strStdOut & oExec.StdOut.ReadLine & vbCrLf 
    Loop 
    Do While Not oExec.StdErr.AtEndOfStream 
     strStdErr = strStdErr & oExec.StdErr.ReadLine & vbCrLf 
    Loop 
    WScript.Sleep 0 
    Loop 
    intErrorLevel = oExec.ExitCode 
    strMessage = strStdOut & strStdErr & CStr(intErrorLevel) 
End If 

WScript.Echo (strMessage) 

注意:更换“的ReadLine”上面“阅读(1)”完成同样的事情,但增加了处理的字符,而不是整行的能力。