How can I execute a command from command line in back ground - vbscript

I have written vb script to run jar command from windows command line in foreground
'File paths
processFile = "java -jar doSomething.jar C:\folder1\subFolder1 C:\folder2\subFolder2"
Set objShell = CreateObject("Wscript.shell")
objShell .run "cmd /k CD C:\VBScriptfolder\script" 'Path to vbscript which contains command to run from command line
WScript.Sleep 5000
Wait(5)
objShell .SendKeys processFile
WScript.Sleep 3000
Wait(3)
objShell .SendKeys "{ENTER}"
WScript.Sleep 40000
Wait(60)
objShell .SendKeys "exit{ENTER}"
But my question is that how to run above command from command line which execute the command in background instead of foreground.

Try to build your command line and debug it with wscript.echo.
And, if you feel that it is correct , you should comment the wscript.echo and uncomment this line Call Run(StrCmd,0,False) 'Hiding the console
Option Explicit
Dim StrCmd,Path,processFile
Path = "C:\VBScriptfolder\script" 'Path to vbscript which contains command to run from command line
processFile = "java -jar doSomething.jar C:\folder1\subFolder1 C:\folder2\subFolder2"
StrCmd = "CD /D "& Path & " & " & processFile &""
wscript.echo StrCmd
'Call Run(StrCmd,1,False) 'Showing the console
'Call Run(StrCmd,0,False) 'Hiding the console
'**********************************************************************************************
Function Run(StrCmd,Console,bWaitOnReturn)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
'A value of 0 to hide the MS-DOS console
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
'MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
'A value of 1 to show the MS-DOS console
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
'MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function
'**********************************************************************************************

Related

How do I convert the weekday command so that I can manually pick the day for each task rather than it detecting it automatically?

When I started on this I wasn't aware that I had to be able to select each daily task manually and pick each task whenever I want, I'm trying to figure out how to convert it into a manual entry so I don't have to rework the whole thing, bear in mind I'm very new to vbscript so if there's an obvious solution I apologize. I'm still working on the later days of the week to finish this.
dtmToday = Date()
dtmDayOfWeek = DatePart("w", dtmToday)
'Select case to pickup the value of day of the week and call procedure
Select Case dtmDayOfWeek
Case 1
Call Sunday()
Case 2
Call Monday()
Case 3
Call Tuesday()
Case 4
Call Wednesday()
Case 5
Call Thursday()
Case 6
Call Friday()
Case 7
Call Saturday()
End Select
'Sunday procedure will execute from select case
sub Sunday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' Execute the command and append to the text file
WShShell.run "cmd /c ping -n 10 youtube.com >> ping.txt", hidden
wscript.quit
End sub
'Monday procedure will execute from select case
sub Monday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' to execute the command and append to the text file using >> if you want to text to be overriden use >
WShShell.run "cmd /c netstat >> netstat.txt", hidden
wscript.quit
End sub
'Tuesday procedure will execute from select case
sub Tuesday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' to execute the command and append to the text file using >> if you want to text to be overriden use >
WShShell.run "cmd /c arp -a >> arp.txt", hidden
wscript.quit
End sub
sub Wednesday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
WShShell.run "cmd /c nbstat -n >> nbstat.txt", hidden
wscript.quit
End Sub
sub Thursday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
WShShell.run "cmd /c tracert -n 10 youtube.com >> nbstat.txt", hidden
wscript.quit
End Sub
You need first optimize your code to avoid heavy duplication as #Lankymart was mentioned it in his comment, by writing one function and call it when you need it, and to store all your commands into an array for easy access by their index.
So your code can be written like that :
Option Explicit
' We define our Global variables
Dim Title,ArrCommands,strcmd,dtmDayOfWeek,IndexCommand,UserInput
Title = "Run command line based on the Day Of Week"
'----------------------------------------------------------------------------------
' We define and store our commands lines into an array
ArrCommands = Array(_
"ping -n 10 youtube.com >> ping.txt",_
"netstat >> netstat.txt",_
"arp -a >> arp.txt",_
"Color 0A & Title Running nbtstat command & nbtstat -n",_
"Color 0A & Title Running Tracert command & tracert youtube.com",_
"Color 0A & Title Running Ipconfig command & Ipconfig /all",_
"Color 0A & Title Running netstat command & netstat -ano"_
)
'-------------------------------Main Program---------------------------------------
Do While Not IsDate(UserInput)
UserInput = InputBox("Type a date here example 24/06/2020",Title,"24/06/2020")
dtmDayOfWeek = MyWeekday(UserInput)
IndexCommand = dtmDayOfWeek - 1
Loop
MsgBox "Day of the Week = "& dtmDayOfWeek & vbCrlf &_
"The command will be executed is : "& ArrCommands(IndexCommand),vbInformation,Title
'Select case to pickup the value of day of the week
Select Case dtmDayOfWeek
Case 1
Call Execute(ArrCommands(IndexCommand),0)
Case 2
Call Execute(ArrCommands(IndexCommand),0)
Case 3
Call Execute(ArrCommands(IndexCommand),0)
Case 4
Call Execute(ArrCommands(IndexCommand),1)
Case 5
Call Execute(ArrCommands(IndexCommand),1)
Case 6
Call Execute(ArrCommands(IndexCommand),1)
Case 7
Call Execute(ArrCommands(IndexCommand),1)
End Select
'MsgBox "Command line is done",vbInformation,Title
'----------------------------------------------------------------------------------
Function MyWeekday(MyDate)
If MyDate = "" Then MyDate = Date()
If IsDate(MyDate) Then
MyWeekDay = Weekday(MyDate)
Exit Function
End If
End Function
'----------------------------------------------------------------------------------
Sub Execute(StrCmd,Console)
Dim ws,MyCmd
Set ws = CreateObject("wscript.Shell")
'The console = 0 means will be running in hidden mode
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & " "
ws.run MyCmd,Console,True
End If
'The console = 1 means will be running in not hidden mode
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & " "
ws.run MyCmd,Console,True
End If
End Sub
'----------------------------------------------------------------------------------

Microsoft VBScript runtime error: Path not found

I want to execute a vbs script which provides me the size of a given folder but at the execution it returns me the error:
Microsoft VBScript runtime error: Path not found
Previously, the error was
Microsoft VBScript runtime error: Permission denied
but after these commands:
takeown /f C:\Users /r /d y
icacls C:\Users /grant administrators:F /T
it turned into "path not found". As you can see the folder that I want the size is C:\Users.
Here's my code:
'Created the 18.03.2010
'Easy script for check space folder. You need NRPE_NT daemon on win computer
'##########################################################'
'Install'
'##########################################################'
'1.copy file to c:\ for example... c:\nrpe_nt\bin\check_folder_size.vbs'
'2.set your nrpe.cfg for command for example
'command[check_foldersize]=c:\windows\system32\cscript.exe //NoLogo //T:30 c:\nrpe_nt\bin\check_folder_size.vbs c:\yourfolder 50 78
'50 70 are parameters for warning and critical value in MB'
'3.restart your nrpe_nt daemon in command prompt example.. net stop nrpe_nt and net start nrpe_nt'
'4. try from linux example.: ./check_nrpe -H yourcomputer -c check_foldersize and result can be OK:22,8 MB'
'it is all'
'##########################################################'
Dim strfolder
Dim intwarning
Dim intcritic
Dim wsh
Dim intvelkost
Dim intjednotka
'##########################################################'
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wsh = CreateObject("WScript.Shell")
'##########################################################'
If WScript.Arguments.Count = 3 Then
strfolder = WScript.Arguments(0)
intwarning = WScript.Arguments(1)
intcritic = WScript.Arguments(2)
Set objFolder = objFSO.GetFolder(strfolder)
intjednotka = 1048576 '1MB->bytes'
intvelkost = objFolder.Size/intjednotka
If (objFolder.Size/1048576) > CInt(intwarning) Then
WScript.Echo "WARNING:" & round (objFolder.Size / 1048576,1) & " MB"
WScript.Quit(1)
ElseIf (objFolder.Size/1024000) > CInt(intcritic) Then
WScript.Echo "CRITICAL:" & Round(objFolder.Size / 1048576,1) & " MB"
WScript.Quit(2)
Else
WScript.Echo "OK:" & Round(objFolder.Size /1048576,1) & " MB"
WScript.Quit(0)
End If
Else
WScript.Echo "UNKNOWN:"& strfolder &"-" & intwarning & "-" & intcritic
WScript.Quit(3)
End If
The line of the call of the script:
check_foldersize = cscript.exe //nologo //T:60 scripts\check_folder_size.vbs C:\Users 4000 5000
Edit: One more useful point : There are no errors when I change the folder C:\Users to C:\Intel for example. So it seems to be a problem linked to the Users folder itself. Then I don't think that iis_iusrs permissions are the cause.

Run Rscript.exe with VBScript and spaces in path

I have the followaing run.vbs script
Rexe = "R-Portable\App\R-Portable\bin\Rscript.exe"
Ropts = "--no-save --no-environ --no-init-file --no-restore --no-Rconsole "
RScriptFile = "runShinyApp.R"
Outfile = "ShinyApp.log"
startChrome = "GoogleChromePortable\App\Chrome-bin\chrome.exe --app=http://127.0.0.1:9999"
strCommand = Rexe & " " & Ropts & " " & RScriptFile & " 1> " & Outfile & " 2>&1"
intWindowStyle = 0 ' Hide the window and activate another window.'
bWaitOnReturn = False ' continue running script after launching R '
' the following is a Sub call, so no parentheses around arguments'
CreateObject("Wscript.Shell").Run strCommand, intWindowStyle, bWaitOnReturn
WScript.Sleep 1000
CreateObject("Wscript.Shell").Run startChrome, intWindowStyle, bWaitOnReturn
It works pretty well in most cases except when the user puts the run.vbs script in a folder with spaces in its name: e.g. if run.vbs is in folder "foo bar", the user gets the error : "C:\Users\[user name]\Desktop\foo" not recognized as internal command...
I don't understand why Rscript.exe looks for the absolute path before running even if it's called from its parent directory using relative path.
I heard about the double quote solution using the absolute path but it doesn't seem to work with .exe scripts (it does though with .bat and .cmd)
Thanks for any help!
Below code will help you
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec("C:\Program Files\R\R-3.2.3\bin\Rscript.exe C:\subfolder\YourScript.R " & """" & var1 & """")
Set oOutput = oExec.StdOut
handle the results as they are written to and read from the StdOut object
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend

How can I redirect my vbscript output to a file using batch file?

I am new to Windows Scripting. I have a simple script for archiving using WinRAR CLI utility. I have to schedule this script using batch file. During archiving there are some errors and I want them to write in a simple text file or at least I can write entire output of archiving in a file. How can I change my code to do this?
Dim MyDate
Dim OutputFile
const WaitUntilFinished = true, DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0
MyDate = Replace(Date, "/", "-")
OutputFile = "backup-" & mydate & ".rar"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.CurrentDirectory = "C:\Users\ABC\Desktop\"
objShell.Run "C:\windows\Rar.exe a .\VBScripts\backups\" & OutputFile & " software", ShowWindow, WaitUntilFinished
objShell.Popup "Archiving Completed Successfully!",5, "Scheduled Backup"
Set objShell = Nothing
Batch file is like this;
#echo off
start /wait C:\Users\ABC\Desktop\VBScripts\scheduled_backup.vbs
Change your command line to include redirection to a log file:
logfile = "C:\path\to\your.log"
objShell.Run "%COMSPEC% /c C:\windows\Rar.exe a .\VBScripts\backups\" & _
OutputFile & " software >""" & logfile & """", ShowWindow, WaitUntilFinished
Use this function instead of WScript.Shell.Run:
' Runs an external program and pipes it's output to
' the StdOut and StdErr streams of the current script.
' Returns the exit code of the external program.
Function Run (ByVal cmd)
Dim sh: Set sh = CreateObject("WScript.Shell")
Dim wsx: Set wsx = Sh.Exec(cmd)
If wsx.ProcessID = 0 And wsx.Status = 1 Then
' (The Win98 version of VBScript does not detect WshShell.Exec errors)
Err.Raise vbObjectError,,"WshShell.Exec failed."
End If
Do
Dim Status: Status = wsx.Status
WScript.StdOut.Write wsx.StdOut.ReadAll()
WScript.StdErr.Write wsx.StdErr.ReadAll()
If Status <> 0 Then Exit Do
WScript.Sleep 10
Loop
Run = wsx.ExitCode
End Function
Call script instead of start in your batch and use redirection:
script //nologo C:\Users\ABC\Desktop\VBScripts\scheduled_backup.vbs 2> errors.txt

VBSCRIPT: TRACERT and PING a WEBADDRESS and write to text file without command promot popup

I need to write a diagnostic utility in VBS which i will package in my windows application installer.
I want the utility to run silently when the user is installing the application.
I tried:
Set pingCXS = objShell.Run("tracert -h 9 webaddress", 0, True)
Set pingCXSOutput = pingCXS.StdOut
strpingCXSOutput = pingCXSOutput.ReadAll
but it returns only the error code not the whole ping information.
When i use run method it gives a command window pop up:
Any other method to traceRT the webaddress without windows popup?
Also using a batch file is not a good option for me, as i have to use some WMI queries in the utility, which will require admin rights in batch file...
Please help out
Try this code :
Option Explicit
Dim ws,fso,TmpLogFile,Logfile,MyCmd,Webaddress,Param
Set ws = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
TmpLogFile = "TmpFile.txt"
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "log"
If fso.FileExists(LogFile) Then fso.DeleteFile LogFile
webaddress = "www.stackoverflow.com"
Param = "-h 9"
MyCmd = "Tracert " & Param & " " & Webaddress & " >> "& TmpLogFile &_
" & cmd /U /C Type " & TmpLogFile & " > " & LogFile & " & Del " & TmpLogFile & ""
Call Run(MyCmd,0,True)
ws.run LogFile
'**********************************************************************************************
Function Run(StrCmd,Console,bWaitOnReturn)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
'A value of 0 to hide the MS-DOS console
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
'A value of 1 to show the MS-DOS console
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function

Resources