VBS Run cmd.exe output to a variable; not text file

前端 未结 2 1961
有刺的猬
有刺的猬 2021-01-13 19:47

This is what I have so far. It works; outputing the folder path to temp to a text file. What I really want, is to output the data to a variable. Every example I see online

2条回答
  •  一个人的身影
    2021-01-13 20:01

    Of course Wscript.Shell would be a lot easier, but, since you want more fine grain control of your session, consider using Win32_Process. Usually, one uses this to control the placement of a new window, but, in your case, you want it hidden, so I set startupInfo.ShowWindow = 0 which means SW_HIDE. The following declares a VBScript function called RunCmd and which will run a command in an invisible window saving the output to a text file and then return the contents of the text file to the caller. As an example, I invoke RunCmd with the HOSTNAME command:

    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")
    

    References:

    • Create method of the Win32_Process class
    • Win32_ProcessStartup class

提交回复
热议问题