使用VbScript静默运行命令行并获取输出?

时间:2011-04-16 22:41:01

标签: command-line vbscript silent

我希望能够通过命令行运行程序,我想用VbScript启动它。我还想获取命令行的输出并将其分配给变量,我希望所有这些都可以在没有cmd窗口弹出的情况下以静默方式完成。我分别管理了两件事但不在一起。这是我到目前为止所得到的。 从cmd运行命令并获取输出:

Dim WshShell, oExec
Set WshShell = WScript.CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("C:\snmpget -c public -v 2c 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.5.1")
x = oExec.StdOut.ReadLine
Wscript.Echo x

上面的脚本可以正常工作并执行我想要的操作,只是cmd会弹出一小段时间。

这是一个静默运行但不会获取输出的脚本

Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\snmpset -c public -v 2c -t 0 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.7.1 i 1", 0, true)

有没有办法让这两个人一起工作?

让我告诉你我为什么要这样做的背景。我基本上每隔5-10分钟对一个单元进行一次轮询,我会在发生某种情况时让脚本发送电子邮件或抛出一个消息框,但我不希望看到cmd行整天在我的计算机上弹出。有什么建议? 感谢

6 个答案:

答案 0 :(得分:34)

您可以将输出重定向到文件,然后读取文件:

return = WshShell.Run("cmd /c C:\snmpset -c ... > 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

答案 1 :(得分:10)

我已经采用了这个和其他各种注释,并为运行应用程序和获取输出创建了一个更高级的功能。

调用函数的示例:将仅为目录输出C:\的DIR列表。输出将返回到变量CommandResults,并保留在C:\ OUTPUT.TXT中。

CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)

功能

Function vFn_Sys_Run_CommandOutput (Command, Wait, Show, OutToFile, DeleteOutput, NoQuotes)
'Run Command similar to the command prompt, for Wait use 1 or 0. Output returned and
'stored in a file.
'Command = The command line instruction you wish to run.
'Wait = 1/0; 1 will wait for the command to finish before continuing.
'Show = 1/0; 1 will show for the command window.
'OutToFile = The file you wish to have the output recorded to.
'DeleteOutput = 1/0; 1 deletes the output file. Output is still returned to variable.
'NoQuotes = 1/0; 1 will skip wrapping the command with quotes, some commands wont work
'                if you wrap them in quotes.
'----------------------------------------------------------------------------------------
  On Error Resume Next
  'On Error Goto 0
    Set f_objShell = CreateObject("Wscript.Shell")
    Set f_objFso = CreateObject("Scripting.FileSystemObject")
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
      'VARIABLES
        If OutToFile = "" Then OutToFile = "TEMP.TXT"
        tCommand = Command
        If Left(Command,1)<>"""" And NoQuotes <> 1 Then tCommand = """" & Command & """"
        tOutToFile = OutToFile
        If Left(OutToFile,1)<>"""" Then tOutToFile = """" & OutToFile & """"
        If Wait = 1 Then tWait = True
        If Wait <> 1 Then tWait = False
        If Show = 1 Then tShow = 1
        If Show <> 1 Then tShow = 0
      'RUN PROGRAM
        f_objShell.Run tCommand & ">" & tOutToFile, tShow, tWait
      'READ OUTPUT FOR RETURN
        Set f_objFile = f_objFso.OpenTextFile(OutToFile, 1)
          tMyOutput = f_objFile.ReadAll
          f_objFile.Close
          Set f_objFile = Nothing
      'DELETE FILE AND FINISH FUNCTION
        If DeleteOutput = 1 Then
          Set f_objFile = f_objFso.GetFile(OutToFile)
            f_objFile.Delete
            Set f_objFile = Nothing
          End If
        vFn_Sys_Run_CommandOutput = tMyOutput
        If Err.Number <> 0 Then vFn_Sys_Run_CommandOutput = "<0>"
        Err.Clear
        On Error Goto 0
      Set f_objFile = Nothing
      Set f_objShell = Nothing
  End Function

答案 2 :(得分:0)

@Mark Cidade

谢谢马克!这解决了几天的研究,想知道如何从PHP WshShell中调用它。谢谢你的代码,我想......

function __exec($tmppath, $cmd)
{
   $WshShell = new COM("WScript.Shell");
   $tmpf = rand(1000, 9999).".tmp"; // Temp file
   $tmpfp = $tmppath.'/'.$tmpf; // Full path to tmp file

   $oExec = $WshShell->Run("cmd /c $cmd -c ... > ".$tmpfp, 0, true);

   // return $oExec == 0 ? true : false; // Return True False after exec
   return $tmpf;
}

在我的案例中,这对我有用。您可以根据自己的需要随意使用和修改。您始终可以在函数中添加功能以自动读取tmp文件,将其分配给变量和/或将其返回,然后删除tmp文件。 再次感谢@Mark!

答案 3 :(得分:0)

对于这一切我还很陌生,但是我发现,如果脚本是通过CScript.exe(控制台脚本宿主)启动的,则exec()上没有弹出窗口:因此运行时:

cscript myscript.vbs //nologo

myscript.vbs中的任何.Exec()调用都不会打开额外的窗口,这意味着 您可以使用原始解决方案的第一个变体(使用exec)。

(请注意,以上代码中的两个正斜杠是有意的,请参见cscript /?)

答案 4 :(得分:-1)

或者查找将输出分配给剪贴板(在第一个脚本中),然后在第二个脚本中解析剪贴板值。

如果你有任何其他方法,请建议我。

答案 5 :(得分:-1)

Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
 Dim filepath As String = path + "\" + "your.bat"
    ' Create the file if it does not exist. 
    If File.Exists(filepath) = False Then
        File.Create(filepath)
    Else
    End If
    Dim attributes As FileAttributes
    attributes = File.GetAttributes(filepath)
    If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
        ' Remove from Readonly the file.
        attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
        File.SetAttributes(filepath, attributes)
        Console.WriteLine("The {0} file is no longer RO.", filepath)
    Else
    End If
    If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
        ' Show the file.
        attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
        File.SetAttributes(filepath, attributes)
        Console.WriteLine("The {0} file is no longer Hidden.", filepath)
    Else
    End If
    Dim sr As New StreamReader(filepath)
    Dim input As String = sr.ReadToEnd()
    sr.Close()
    Dim output As String = "@echo off"
    Dim output1 As String = vbNewLine + "your 1st cmd code"
    Dim output2 As String = vbNewLine + "your 2nd cmd code "
    Dim output3 As String = vbNewLine + "exit"
    Dim sw As New StreamWriter(filepath)
    sw.Write(output)
    sw.Write(output1)
    sw.Write(output2)
    sw.Write(output3)
    sw.Close()
    If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
    Else
        ' Hide the file.
        File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
        Console.WriteLine("The {0} file is now hidden.", filepath)
    End If
    Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
    procInfo.WindowStyle = ProcessWindowStyle.Minimized
    procInfo.WindowStyle = ProcessWindowStyle.Hidden
    procInfo.CreateNoWindow = True
    procInfo.FileName = path + "\" + "your.bat"
    procInfo.Verb = "runas"
    Process.Start(procInfo)

它将.bat文件保存到&#34;当前用户的应用数据&#34; ,如果它不存在并删除属性 然后设置&#34;隐藏&#34;写入cmd代码后的文件属性 并以静默方式运行它并捕获所有输出将其保存到文件 所以如果你想将cmd的所有输出保存到文件中,只需添加你的喜欢这个

code > C:\Users\Lenovo\Desktop\output.txt

只需替换word&#34; code&#34;使用.bat文件代码或命令,然后输出文件的目录 我在搜索了很多之后最近发现了一个代码 如果你想在vb或c#或简单地运行.bat文件 只需按照我编写的方式添加此内容