I need execute a command line in a Visual Basic Script

77,467

Solution 1

Try something like this:

Dim objShell
Set objShell = WScript.CreateObject ("WScript.shell")
objShell.run "cmd /c ver"
Set objShell = Nothing

EDIT:

Well then you can redirect output to a file and then read the file:

return = WshShell.Run("cmd /c ver > c:\temp\output.txt", 0, true)

Set fso  = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close

Solution 2

There is a way to do this without having to write output to a file.

For example, suppose you wanted to capture the text of a directory listing. (There would be lots of better ways to get it than this, but I'm just using a simple example.)

With the function below in your VBScript, you could enter:

thisDir = getCommandOutput("cmd /c dir c:")

And when the above line is executed, the variable "thisDir" would contain the output from the DIR command.

Note that some commands you want output from will require you to pass them through the command shell (the "cmd /c" part of the above), while others may work fine if you run them directly without the shell. Try it without the command shell. If it fails, try it with the command shell.

'
' Capture the results of a command line execution and
' return them to the caller.
'
Function getCommandOutput(theCommand)

    Dim objShell, objCmdExec
    Set objShell = CreateObject("WScript.Shell")
    Set objCmdExec = objshell.exec(thecommand)
    getCommandOutput = objCmdExec.StdOut.ReadAll

end Function

Solution 3

Dim shell
Set shell= WScript.CreateObject ("WScript.shell")
shell.Exec"cmd /c ver"
Set shell= Nothing
Share:
77,467
user1528355
Author by

user1528355

Updated on July 09, 2022

Comments

  • user1528355
    user1528355 almost 2 years

    I need to execute the command "ver" in my vbs to see the version of my Operating System, and i don't know how make it.

    I tried this, but dont work:

    Function ExecuteWithTerminalOutput(cmd)
    Set shell = WScript.CreateObject("WScript.Shell")
    Set Exec =  shell.Exec("ver")
    End Function
    
  • user1528355
    user1528355 almost 12 years
    ok nice, it works, but i need the result in a var, to use in a If, can i do this? Thanks for help!
  • user1528355
    user1528355 almost 12 years
    Thanks bro! It work! One thing, the ";" dont need it. Nice help and too fast!