37

我希望能够通过命令行运行一个程序,并且我想用 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 行整天在我的计算机上弹出。有什么建议么?谢谢

4

7 回答 7

40

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

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
于 2011-04-16T22:58:34.680 回答
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
于 2012-09-21T20:21:23.680 回答
1

我对这一切都很陌生,但我发现如果脚本是通过 CScript.exe (控制台脚本主机)启动的,则 exec() 上不会弹出窗口:所以在运行时:

cscript myscript.vbs //nologo

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

(注意上面代码中的两个正斜杠是故意的,见cscript /?)

于 2018-12-18T16:56:53.967 回答
1

在这里,我找到了一个对我有用的解决方案:

set wso = CreateObject("Wscript.Shell")
set exe = wso.Exec("cmd /c dir /s /b d:\temp\*.jpg")
sout = exe.StdOut.ReadAll
于 2021-10-18T05:08:33.307 回答
0

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

于 2011-12-13T06:43:53.370 回答
-1

@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!

于 2014-11-24T00:37:32.133 回答
-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 文件保存到“当前用户的 Appdata”,如果它不存在并删除属性,然后在编写 cmd 代码后将“隐藏”属性设置为文件并静默运行并捕获所有输出并将其保存到文件,所以如果你想将 cmd 的所有输出保存到文件中,只需像这样添加你的

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

只需用您的 .bat 文件代码或命令替换单词“code”,然后在输出文件的目录中,如果您想在 vb 或 c# 中运行 .bat 文件,我最近在搜索了很多之后找到了一个代码,或者只是以相同的方式添加它我在其中写过

于 2015-06-21T10:51:51.580 回答