How to show DOS output when using vbscript Exec - command-line

I have the following VBScript:
Set Shell = WScript.CreateObject("WScript.Shell")
commandLine = puttyPath & "\plink.exe -v" & " -ssh" [plus additional commands here]
Set oExec = Shell.Exec(commandLine)
This causes a DOS window to appear but the output from plink.exe is not displayed. Is there any way to get the DOS window to display this output?

Windows scripting host lacks a system() command so you have to implement your own, IMHO my helper function is superior to stealthyninja's version since it waits for process exit and not just empty stdout and it also handles stderr:
Function ExecuteWithTerminalOutput(cmd)
Set sh = WScript.CreateObject("WScript.Shell")
Set exec = sh.Exec(cmd)
Do While exec.Status = 0
WScript.Sleep 100
WScript.StdOut.Write(exec.StdOut.ReadAll())
WScript.StdErr.Write(exec.StdErr.ReadAll())
Loop
ExecuteWithTerminalOutput = exec.Status
End Function
call ExecuteWithTerminalOutput("cmd.exe /c dir %windir%\*")

Try --
Set Shell = WScript.CreateObject("WScript.Shell")
commandLine = puttyPath & "\plink.exe -v" & " -ssh" [plus additional commands here]
Set oExec = Shell.Exec(commandLine)
Set oStdOut = oExec.StdOut
While Not oStdOut.AtEndOfStream
sLine = oStdOut.ReadLine
WScript.Echo sLine
Wend

The correct way is :
Set Shell = WScript.CreateObject("WScript.Shell")
commandLine = puttyPath & "\plink.exe -v" & " -ssh" [plus additional commands here]
Set oExec = Shell.Exec(commandLine)
Set oStdOut = oExec.StdOut
While Not oStdOut.AtEndOfStream
sLine = oStdOut.ReadLine
WScript.Echo sLine
Wend
Or:
Set Shell = WScript.CreateObject("WScript.Shell")
commandLine = puttyPath & "\plink.exe -v" & " -ssh" [plus additional commands here]
Set oExec = Shell.Exec(commandLine)
WScript.Echo oExec.StdOut.ReadAll

Related

VBScript - Checking if port is listening + window to notify user

I got a question regarding vbs.
I need to monitor if a connection on the port 5900 is established or not.
The Script should run as a service, and should check frequently if the connection is established or not.
When the connection is established, it should open a small window(that has no user interaction allowed( e.g. cant be closed, has no "ok" button, etc.)), that contains sth. like "Connection established // [Hostname of the device thats connected].
If the connection has been closed, then the small window should also be closed.
ATM i got it to work to pop-up a message, if i run the script and there is an established connection
My code so far:
Dim ObjExec
Dim strFromProc
Set objShell = CreateObject("WScript.Shell")
Set ObjExec = objShell.Exec("%comspec% /c netstat -a | find ""ESTABLISHED"" | find "":5900""" )
Do Until ObjExec.Stdout.atEndOfStream
strFromProc = strFromProc & ObjExec.StdOut.ReadLine & vbNewLine
WScript.Echo "Connection Established"
Loop
Best Regards
Try something like that : using .Popup method
Option Explicit
Dim ObjExec,objShell,strFromProc,intButton,Port
Port = "5900"
Set objShell = CreateObject("WScript.Shell")
Set ObjExec = objShell.Exec("%comspec% /c netstat -a | find "& DblQuote("ESTABLISHED") & "| find " & DblQuote(Port) &"")
strFromProc = ObjExec.StdOut.ReadAll
If Instr(strFromProc,"ESTABLISHED") > 0 Then
intButton = objShell.Popup(strFromProc,3,"Connection Established # Port "& Port &"",vbInformation)
Else
intButton = objShell.Popup("Connection Not Established # Port "& Port,3,"Connection Not Established # Port "& Port &"",vbExclamation)
End If
'****************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************************
And if you like to avoid shwoing the black console; try this method :
Option Explicit
Dim ObjExec,strCommand,OutPutData,objShell,strFromProc,intButton,Port
Port = "5900"
Set objShell = CreateObject("WScript.Shell")
strCommand = "%comspec% /c netstat -a | find "& DblQuote("ESTABLISHED") & "| find " & DblQuote(Port) &""
OutPutData = Run_Cmd(strCommand)
If Instr(OutPutData,"ESTABLISHED") > 0 Then
intButton = objShell.Popup(OutPutData,3,"Connection Established # Port "& Port &"",vbInformation)
Else
intButton = objShell.Popup("Connection Not Established # Port "& Port,3,"Connection Not Established # Port "& Port &"",vbExclamation)
End If
'****************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************************
Function Run_Cmd(strCommand)
On Error Resume Next
Const ForReading = 1
Const TemporaryFolder = 2
Const WshHide = 0
Dim wsh, fs, ts
Dim strTempFile,strFile, strData
Set wsh = CreateObject("Wscript.Shell")
Set fs = CreateObject("Scripting.FileSystemObject")
strTempFile = fs.BuildPath(fs.GetSpecialFolder(TemporaryFolder).Path, fs.GetTempName)
strFile = fs.BuildPath(fs.GetSpecialFolder(TemporaryFolder).Path, "result.txt")
wsh.Run "cmd.exe /c " & strCommand & " > " & DblQuote(strTempFile) & "2>&1", WshHide, True
wsh.Run "cmd.exe /u /c Type " & DblQuote(strTempFile) & " > " & DblQuote(strFile) & "", WshHide, True
Set ts = fs.OpenTextFile(strFile, ForReading,true,-1)
strData = ts.ReadAll
Run_Cmd = strData
ts.Close
fs.DeleteFile strTempFile
fs.DeleteFile strFile
End Function
'****************************************************************

vbscript to run command

I'm trying to create a script that runs the command: RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Right now this errors out
Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")
sEXE = """C:\Windows\system32\RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255 """
with CreateObject("WScript.Shell")
.Run sEXE & " " , 1, true
end with
Wscript.Quit
Any suggestions? Could I make the script so I could run a bunch of commands and wait until each process executed has finished before executing the other command?
The command line should appear exactly as it would if you typed it at the command prompt (verify by Wscript.Echo sEXE):
sEXE = """C:\Windows\system32\RunDll32.exe"" InetCpl.cpl,ClearMyTracksByProcess 255"

Execute Process and Redirect Output

I run a process using VBScript. The process usually takes 5-10 minutes to finish and if i run the process standalone then it gives intermittent output while running.
I want to acheive the same logic while running the process using VBScript. Can some one please tell me how to do that?
Set Process = objSWbemServices.Get("Win32_Process")
result = Process.Create(command, , , intProcessID)
waitTillProcessFinishes objSWbemServices,intProcessID
REM How to get the output when the process has finished or while it is running
You don't have access to the output of processes started via WMI. What you could do is redirect the output to a file:
result = Process.Create("cmd /c " & command & " >C:\out.txt", , , intProcessID)
and read the file periodically:
Set fso = CreateObject("Scripting.FileSystemObject")
linesRead = 0
qry = "SELECT * FROM Win32_Process WHERE ProcessID=" & intProcessID
Do While objSWbemServices.ExecQuery(qry).Count > 0
Set f = fso.OpenTextFile("C:\out.txt")
Do Until f.AtEndOfStream
For i = 1 To linesRead : f.SkipLine : Next
WScript.Echo f.ReadLine
linesRead = linesRead + 1
Loop
f.Close
WScript.Sleep 100
Loop
The above is assuming the process is running on the local host. If it's running on a remote host you need to read the file from a UNC path.
For local processes the Exec method would be an alternative, since it gives you access to the process' StdOut:
Set sh = CreateObject("WScript.Shell")
Set p = sh.Exec(command)
Do While p.Status = 0
Do Until p.StdOut.AtEndOfStream
WScript.Echo p.StdOut.ReadLine
Loop
WScript.Sleep 100
Loop
WScript.Echo p.StdOut.ReadAll

Checksum of file in vbscript

I have the following command
"C:\Program Files\File Checksum Integrity Verifier\fciv.exe" -sha1 "D:\new.txt"
How to run this command from vbscript? Can anybody help me?
VBScript comes with a couple of different ways to execute command lines, both of which are on the WshShell object (WScript.Shell)
Using WshShell.Exec
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("""C:\Program Files\File Checksum Integrity Verifier\fciv.exe"" -sha1 ""D:\new.txt""")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
WScript.Echo oExec.Status
Using WshShell.Run
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run """C:\Program Files\File Checksum Integrity Verifier\fciv.exe"" -sha1 ""D:\new.txt""", 1, true

Running command line silently with VbScript and getting output?

I want to be able to run a program through command line and I want to start it with VbScript. I also want to get the output of the command line and assign it to a variable and I want all this to be done silently without cmd windows popping up. I have managed two things separately but not together. Here's what I got so far.
Run the command from cmd and get output:
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
The above script works and does what I want except that cmd pops up for a brief moment.
Here's a script that will run silently but won't grab the output
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)
Is there a way to get these two to work together?
Let me give you a background on why I want do to this. I am basically polling a unit every 5-10 minutes and I am going to get the script to email or throw a message box when a certain condition occurs but I don't want to see cmd line popping up all day long on my computer. Any suggestions?
Thanks
You can redirect output to a file and then read the file:
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
I have taken this and various other comments and created a bit more advanced function for running an application and getting the output.
Example to Call Function: Will output the DIR list of C:\ for Directories only. The output will be returned to the variable CommandResults as well as remain in C:\OUTPUT.TXT.
CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)
Function
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
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning
that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
Here I found a solution, which works for me:
set wso = CreateObject("Wscript.Shell")
set exe = wso.Exec("cmd /c dir /s /b d:\temp\*.jpg")
sout = exe.StdOut.ReadAll
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
#Mark Cidade
Thanks Mark! This solved few days of research on wondering how should I call this from the PHP WshShell. So thanks to your code, I figured...
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;
}
This is what worked for me in my case. Feel free to use and modify as per your needs. You can always add functionality within the function to automatically read the tmp file, assign it to a variable and/or return it and then delete the tmp file.
Thanks again #Mark!
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)
it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes
and after that set the "hidden" attributes to file after writing your cmd code
and run it silently and capture all output saves it to file
so if u wanna save all output of cmd to file just add your like this
code > C:\Users\Lenovo\Desktop\output.txt
just replace word "code" with your .bat file code or command and after that the directory of output file
I found one code recently after searching alot
if u wanna run .bat file in vb or c# or simply
just add this in the same manner in which i have written