【问题标题】:I need execute a command line in a Visual Basic Script我需要在 Visual Basic 脚本中执行命令行
【发布时间】:2012-07-15 02:35:32
【问题描述】:

我需要在我的vbs中执行命令“ver”来查看我的操作系统的版本,我不知道如何制作。

我试过了,但是不行:

Function ExecuteWithTerminalOutput(cmd)
Set shell = WScript.CreateObject("WScript.Shell")
Set Exec =  shell.Exec("ver")
End Function

【问题讨论】:

    标签: command-line vbscript cmd exec


    【解决方案1】:

    有一种方法可以做到这一点,而不必将输出写入文件。

    例如,假设您想要捕获目录列表的文本。 (有很多比这更好的方法,但我只是用一个简单的例子。)

    在你的VBScript中使用下面的函数,你可以输入:

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

    当执行上述行时,变量“thisDir”将包含 DIR 命令的输出。

    请注意,您想要输出的某些命令将需要您通过命令外壳(上面的“cmd /c”部分)传递它们,而如果您直接在没有外壳的情况下运行它们,其他命令可能会正常工作。在没有命令外壳的情况下尝试它。如果失败,请使用命令 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
    

    【讨论】:

      【解决方案2】:

      试试这样的:

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

      编辑:

      那么您可以将输出重定向到一个文件,然后读取该文件:

      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
      

      【讨论】:

      • 好吧,它可以工作,但我需要一个 var 中的结果,以便在 If 中使用,我可以这样做吗?感谢您的帮助!
      • 谢谢兄弟!这行得通!一件事,“;”不需要它。很好的帮助,太快了!
      【解决方案3】:
      Dim shell
      Set shell= WScript.CreateObject ("WScript.shell")
      shell.Exec"cmd /c ver"
      Set shell= Nothing
      

      【讨论】:

        猜你喜欢
        • 2012-09-19
        • 1970-01-01
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多