37

コマンドラインからプログラムを実行できるようにしたいので、VbScriptでプログラムを開始したいと思います。また、コマンドラインの出力を取得して変数に割り当てたいので、cmdウィンドウがポップアップしないようにこれらすべてをサイレントに実行したいと思います。私は2つのことを別々に管理しましたが、一緒には管理していません。これが私がこれまでに得たものです。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)

これら2つを連携させる方法はありますか?

なぜ私がこれをやりたいのかについての背景を説明しましょう。私は基本的に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を使用)。

(上記のコードの2つのスラッシュは意図的なものであることに注意してください。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

(最初のスクリプトで)クリップボードに出力を割り当ててから、2番目のスクリプトでクリップボードの値を解析します。

于 2011-12-13T06:43:53.370 に答える
-1

@マークシダーデ

ありがとうマーク!これにより、PHPWshShellからこれをどのように呼び出すべきか疑問に思った数日間の調査が解決されました。だからあなたのコードのおかげで、私は考えました...

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ファイルのコードまたはコマンドに置き換えるだけです。その後、出力ファイルのディレクトリをたくさん検索した後、最近1つのコードを見つけました。vbまたはc#で.batファイルを実行するか、同じ方法でこれを追加するだけです。私が書いた

于 2015-06-21T10:51:51.580 に答える