Running command line silently with VbScript and getting output? - command-line

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

Related

Returned string from PowerShell to VBS script is empty [duplicate]

My VBScript does not show the results of any command I execute. I know the command gets executed but I would like to capture the result.
I have tested many ways of doing this, for example the following:
Const WshFinished = 1
Const WshFailed = 2
strCommand = "ping.exe 127.0.0.1"
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(strCommand)
Select Case WshShellExec.Status
Case WshFinished
strOutput = WshShellExec.StdOut.ReadAll
Case WshFailed
strOutput = WshShellExec.StdErr.ReadAll
End Select
WScript.StdOut.Write strOutput 'write results to the command line
WScript.Echo strOutput 'write results to default output
But it does not print any results. How do I capture StdOut and StdErr?
WScript.Shell.Exec() returns immediately, even though the process it starts does not. If you try to read Status or StdOut right away, there won't be anything there.
The MSDN documentation suggests using the following loop:
Do While oExec.Status = 0
WScript.Sleep 100
Loop
This checks Status every 100ms until it changes. Essentially, you have to wait until the process completes, then you can read the output.
With a few small changes to your code, it works fine:
Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
strCommand = "ping.exe 127.0.0.1"
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(strCommand)
Do While WshShellExec.Status = WshRunning
WScript.Sleep 100
Loop
Select Case WshShellExec.Status
Case WshFinished
strOutput = WshShellExec.StdOut.ReadAll()
Case WshFailed
strOutput = WshShellExec.StdErr.ReadAll()
End Select
WScript.StdOut.Write(strOutput) 'write results to the command line
WScript.Echo(strOutput) 'write results to default output
You should read both streams INSIDE the loop as well as after it. When your process is verbose then it will block on the I/O buffer when this buffer will not be emptyfied succesively!!!
I think Tomek's answer is good, but incomplete.
Here's a code example.
Private Sub ExecuteCommand(sCommand$)
Dim wsh As Object
Set wsh = CreateObject("WScript.Shell")
Dim oExec As Object, oOut As TextStream
'Exec the command
Set oExec = wsh.Exec(sCommand$)
Set oOut = oExec.StdOut
'Wait for the command to finish
While Not oOut.AtEndOfStream
Call Debug.Print(oOut.ReadLine)
Wend
Select Case oExec.Status
Case WshFinished
Case WshFailed
Err.Raise 1004, "EndesaSemanal.ExecuteCommand", "Error: " & oExec.StdErr.ReadAll()
End Select
End Sub

Open or close cd-drive using cmd

Whether there is any way to close and open cd-drive using cmd?
I can open it like this:
powershell (New-Object -com "WMPlayer.OCX.7").cdromcollection.item(0).eject()
But idk how to close it
(Of course I can push it in, but i mean how i can close it with cmd)
Found on Google with keywords :
powershell close cd rom drive
http://www.powershellmagazine.com/2013/11/12/pstip-ejecting-and-closing-cdrom-drive-the-powershell-way/
do
Dim ts
Dim strDriveLetter
Dim intDriveLetter
Dim fs 'As Scripting.FileSystemObject
Const CDROM = 4
On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
strDriveLetter = ""
For intDriveLetter = Asc("A") To Asc("Z")
Err.Clear
If fs.GetDrive(Chr(intDriveLetter)).DriveType = CDROM Then
If Err.Number = 0 Then
strDriveLetter = Chr(intDriveLetter)
Exit For
End If
End If
Next
Set oWMP = CreateObject("WMPlayer.OCX.7" )
Set colCDROMs = oWMP.cdromCollection
For d = 0 to colCDROMs.Count - 1
colCDROMs.Item(d).Eject
Next 'null
For d = 0 to colCDROMs.Count - 1
colCDROMs.Item(d).Eject
Next 'null
set owmp = nothing
set colCDROMs = nothing
loop
save as .vbs
you might have to disable antivirus

Excel will not close processes

So, I'm using (after modification) this code, from here: How to set recurring schedule for xlsm file using Windows Task Scheduler
My error: Runtime error: Unknown runtime error.
I've searched far and wide to find an way to close the Excel process, but almost everybody uses .Quit sadly it gives the above error. I've also tried .Close, but that is not recognized
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = "C:\Users\hviid00m\Desktop"
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\Status Report (Boxplots) TEST.xlsm"
Set oWorkBook = myExcelWorker.Workbooks.Open (strWorkerWB, , , , , , True)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "Refresh"
on error resume next
myExcelWorker.Run strMacroName
if err.number <> 0 Then
WScript.Echo "Fejl i macro"
End If
err.clear
on error goto 0
oWorkBook.Save
' Clean up and shut down
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
myExcelWorker.Quit <--- ERROR
Set oWorkBook = Nothing
Set myExcelWorker = Nothing
Set WshShell = Nothing
Found some code on a different side.
The reason why (as far as I understood) is that .Quit and .Close is for VBA not VBS.
' Clean up and shut down
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
Dim objWMIService, objProcess, colProcess
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = " & "'EXCEL.EXE'")
For Each objProcess in colProcess
objProcess.Terminate()
Next`
Set oWorkBook = Nothing
Set myExcelWorker = Nothing
Set WshShell = Nothing

Using a for loop to access Command Prompt

I want to call a function Christian.exe to the command line to act of a series of files that are indexed as "reentrant_008.sif" (8 is an example number).
"Christian.exe reentrant_00" & num & ".sif reentrant_00" & num & ".pgm" 0 2000 is the text that needs to be fed into the command prompt for the program to execute (num is an arbitrary number)
There are approximately 400 files, so I want to create a vbs code that calls the command prompt for each file until all the files have been accessed so far this is my code:
For
Dim cmdpath
num = CStr(i)
Set wshShell = WScript.CreateObject ("WSCript.shell")
If i < 10 Then
cmdpath = "Christian.exe reentrant_00" & num & ".sif reentrant_00" & num & ".pgm" 0 2000
Else
If i < 100 Then
cmdpath = "Christian.exe reentrant_0" & num & ".sif reentrant_0" & num & ".pgm" 0 2000
Else
cmdpath = "Christian.exe reentrant_" & num & ".sif reentrant_" & num & ".pgm" 0 2000
End If
End If
wshshell.run cmdpath
Next
Problem is that a new command prompt is being called for each file, which is slowing down my computer. How do I ensure that only one command window that addresses all my files is called?
If you look at the documentation for Run you will see two option arguments [intWindowStyle], [bWaitOnReturn]. If you want your EXE to wait before proceeding on the script change your call to this
wshshell.run cmdpath, 0, True
Where 0 will hide the window and True will wait for the program to finish before proceeding in the script. Depending on your needs you could change the number or remove it.
wshshell.run cmdpath,, True
Since you tagged your question with both vbscript and powershell I'm adding a PowerShell solution:
foreach ($i in 1..400) {
$num = "{0:d3}" -f $i
& Christian.exe "reentrant_${num}.sif" "reentrant_${num}.pgm" 0 2000
}
& is the call operator. I recommend using it whenever you run external commands in PowerShell, because otherwise you'll be in for a surprise when you try to run a command from a variable for the first time:
$christian = "Christian.exe"
$christian ... # <-- throws an error, because $christian contains a
# string, which is NOT automagically interpreted
# as a command by PowerShell
& $christian ... # <-- works
-f is the formatting operator, that allows you to create formatted string output. Since your command lines only differ by the zero-padding of the input and output files it's better to build the file names with pre-padded number strings.
I recommend doing the pre-padding in VBScript as well:
For i = 1 To 400
num = Right("000" & i, 3)
cmdpath = "Christian.exe reentrant_" & num & ".sif reentrant_" & num & _
".pgm" 0 2000
wshshell.run cmdpath, 0, True
Next

Vbs script to check date and extension

Hi I cant get the below script ive worked on to pickup the extension of the files, Can any help me out by pointing where I have gone wrong?
dim fileSystem, folder, file
dim path
dim count : count = 0
path = "C:\temp"
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(path)
for each file in folder.Files
if file.DateLastModified > dateadd("h", -24, Now) & File.name = "txt" then
count = count + 1
end if
Next
if count < 4 then
Set WshShell = WScript.CreateObject("WScript.Shell")
strcommand = "eventcreate /T ERROR /ID 666 /L Application /SO BESROffsite /D " & _
Chr(34) & count & " Files found please check offsite copy " & Chr(34)
WshShell.Run strcommand
wScript.Quit ( 1001 )
Else
Set WshShell = WScript.CreateObject("WScript.Shell")
strcommand = "eventcreate /T Information /ID 666 /L Application /SO BESROffsite /D " & _
Chr(34) & count & " Files found offsite is working fine " & Chr(34)
WshShell.Run strcommand
wScript.Quit ( 0 )
End if
File.name is the full name including the extension, to test for the extension;
if ... fileSystem.getExtensionName(file.name) = "txt" then
You also want the logical And not the bitwise concatenating & in their too.
Alex's answer is the one you want, but just for reference if you were working just with vbs and a string filename, without the filesystemobject collection you could achieve the same via:
Right(strFilename, Len(strFilename) - Instrrev(strFilename, "."))
This essentially finds the position of the final "." in the filename, takes this away from the length of your filename, and then gives you however many character's that equals from the right hand side. This could be amended slightly to use the "Mid" command rather than the "Right" but I don't think it matters too much in a case like this.