How to run a file on background using vbscript with launch options - vbscript

I need to run a batch file in the background with launch option "1" (so it will %1 in the batch file).
here is my code:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Program Files\Pineapplesoft\Lost computer\lostcomputeraudio.bat" & Chr(34), 0
Set WshShell = Nothing

Use a function to quote strings, and - optionally - a sub to map all elements of an array via a manipulator function to build command lines in a structured/well scaling way; use Join() to put the parts together (with automagical space separator):
Option Explicit
Function qq(s) : qq = """" & s & """" : End Function
Sub mapF(a, f)
Dim i
For i = LBound(a) To UBound(a)
a(i) = f(a(i))
Next
End Sub
Dim sFSpec : sFSpec = "C:\Program Files\Pineapplesoft\Lost computer\lostcomputeraudio.bat"
Dim aParms : aParms = Split("1#/pi:pa po#last parm", "#")
mapF aParms, GetRef("qq")
Dim sCmd : sCmd = Join(Array( _
qq(sFSpec) _
, Join(aParms) _
))
WScript.Echo qq(sCmd)
output:
cscript startaudio.vbs
""C:\Program Files\Pineapplesoft\Lost computer\lostcomputeraudio.bat" "1" "/pi:pap po" "last parm""

The script you ask is as follows:
Set objArgs = Wscript.Arguments
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\Program Files\Pineapplesoft\Lost computer\lostcomputeraudio.bat " & objArgs(0), 0, false)
Save it for example as myscript.vbs.
Note that the parameter 0 in the code means that the window will be hidden. The paremeter false in the code means that the excution of the .vbs will not wait for the .bat to finish.
What will happen is that, the .vbs will start the .bat and finish its execution, leaving the .bat being executed in the background, as you request.
Exeucute it like this:
c:\<whatever>\wscript myscript.vbs <the_parameter>

Related

Use VBS to run a program with parameters

I'm a total vbs novice trying to perform the supposedly simple task of using a vbscript to run a single program (with parameters).
The path the to program is:
C:\Program Files (x86)\SpeedyFox\speedyfox.exe
and the parameter switch that must go with it is:
/Firefox:C:\Program Files\Firefox\Data\profile
If I wrap both sections in quotes (due to the spaces in their paths) it gives the following combined single command:
"C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile"
If I then paste this into Start > Run it works exactly as I want.
I'm just trying to achieve the same thing from a vbs script instead of manually pasting into the Run box.
I do not want the command to run within a CMD console (as other questions on here have asked). All I am trying to do is to get "C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile" to work with the shell.ShellExecute line of the script below.
Set objShell = Wscript.CreateObject ("Wscript.shell")
set shell=CreateObject("Shell.Application")
shell.ShellExecute ** WHAT DO I PUT HERE? **
set shell=nothing
but try as I might, I just keep getting WSH "Expected end of statement" error messages.
1.First : I recommend you Make it a habit to use this quote function
to make it easy for you to quote variables in these situations !
2. Second : You should use MsgBox or Wscript.echo in order to show
and debug your variables easily !
Wscript.echo DblQuote("Hello World !")
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
So, I downloaded this application (speedyfox.exe) and i tested it on my Windows 10 (32bits)
So, here is what i tested and it works like a charm on my side :
Option Explicit
Dim objShell,MyCommand,strProgramFiles,SpeedyFoxfile,Title
Title = "Execute SpeedyFox in Commandline"
Set objShell = CreateObject("Shell.Application")
strProgramFiles = GetProgramFilesPath()
SpeedyFoxfile = strProgramFiles & "\SpeedyFox\speedyfox.exe"
MsgBox "Without Double Quotes" & vbCrlf & SpeedyFoxfile,vbInformation,Title
MsgBox "With Double Quotes" & vbCrlf & DblQuote(SpeedyFoxfile),vbInformation,Title
MyCommand = "CD /D "& DblQuote(strProgramFiles &"\SpeedyFox\") &"&"& DblQuote(SpeedyFoxfile) & " " & DblQuote("/Firefox:default") & " " & DblQuote("/Chrome:Default")
MsgBox MyCommand,vbInformation,Title
Call Execute(MyCommand)
'-----------------------------------------
Function Execute(StrCmd)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
MyCmd = "CMD /K " & StrCmd & ""'
Result = ws.run(MyCmd,1,True)
Execute = Result
End Function
'-----------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'-----------------------------------------
Function GetProgramFilesPath()
Dim ws,OsType,strProgramFiles
Set ws = createObject("WScript.Shell")
OsType = ws.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")
If OsType = "x86" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES%")
elseif OsType = "AMD64" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES(x86)%")
end if
GetProgramFilesPath = strProgramFiles
End Function
'-----------------------------------------
Sigh, reminds me of my vbscript days, now I use Ruby and it's just as simple as
´my_shell_command params´
However, back to your question: the shortest way to use ShellExecute is
CreateObject("Shell.Application").ShellExecute "application", "parameters", "dir", "verb", window
See this documentation for explanation of the parameters.
EDIT:
You have to pay attention at the quotes, they need to be passed to the shell also by using two quotes
eg CreateObject("Shell.Application").ShellExecute "C:\Program Files (x86)\SpeedyFox\speedyfox.exe", """/Waterfox:C:\Program Files\Waterfox\Data\profile"""

Open multiple .vbs one by one

i want .vbs script, to open multiple large files .vbs [i want to Open .vbs one by one] that do not make me, lag in PC.
0001.vbs, 0002.vbs, 0003.vbs, 0004.vbs
is can be different names like:
Anna.vbs, Diana.vbs, Antony.vbs, Andy.vbs
Example:
run C:\0001.vbs
MsgBox "0001.vbs IS END"
Next Open run C:\0002.vbs
MsgBox YES NO
MsgBox "0002.vbs IS END"
Next Open run C:\0003.vbs
MsgBox YES NO
MsgBox "0003.vbs IS END"
Next Open run C:\0004.vbs
MsgBox YES NO
MsgBox "0004.vbs IS END"
Thank you for you help.
Set Shell = CreateObject("WScript.Shell")
For i = 1 To 4
strFile = Right("0000" & i, 4) & ".vbs"
If MsgBox("Would you like to run " & strFile & "?", vbYesNo Or vbQuestion) = vbYes Then
Shell.Run "c:\" & strFile, 1, True
MsgBox strFile & " IS END"
End If
Next
Just make sure you pass True as the last parameter to Shell.Run so that this script waits until the others are done before reporting that they've ended.
Edit: To answer your comment about using names, you can loop through an array created on-the-fly.
For Each strName In Array("Anna", "Diana", "Antony", "Andy")
Next
To not make you wait for each sub process/.vbs before you start the next, don't use the 3rd/wait/true parameter to the .Run method:
a.vbs
Option Explicit
Dim oWSH : Set oWSH = CreateObject("WScript.Shell")
Dim v
For v = 0 To 1
oWSH.Run "cscript.exe " & v & ".vbs", 0, False
Next
MsgBox WScript.ScriptName & " done. " & Now()
0.vbs, 1.vbs
Option Explicit
Randomize
WScript.Sleep Rnd() * 1000
MsgBox WScript.ScriptName & " done. " & Now()
Evidence:
As you can see, a.vbs is finished first and 0.vbs and 1.vbs terminate in random/not in call order.
We have
0001.vbs, 0002.vbs, 0003.vbs, 0004.vbs
Assuming that you have this script file with the after mentioned files in the same directory.
If not, just modify the full path of your vbs files you want to run.
Instead of
WshShell.Run ".\0001.vbs"
You use for example:
WshShell.Run "c:\indel\0001.vbs"
This is the script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run ".\0001.vbs"
WshShell.Run ".\0002.vbs"
WshShell.Run ".\0003.vbs"
WshShell.Run ".\0004.vbs"
What you need to do is make this code
do
msgbox("haha you cant close this")
CreateObject ("WScript.Shell").Run(".\Duplicate.vbs")
loop

vbs/batch folder name with spacing issue

Im having an issue where i am trying to create shortcuts but the vbs script is cutting out when it reaches a space in the path.
i have had a look around but many of the ones i have seen deal with the string being in vbs not being passed from a batch file.
here is my code so you can get a better understanding
Batch File:
#echo off
set office7="C:\ProgramData\Microsoft\Windows\Start Menu\Strategix Programs\Office Programs"
mkdir %office7%
cscript "H:\Installation Batch Files\createLink.vbs" ""%office7%\Purchase Order Entry.lnk"" "\\192.168.0.7\Temp\stock\Porder10.exe" "T:\Stock"
pause
Vbs file:
Set oShell = CreateObject("WScript.Shell") Set args = WScript.Arguments
sShortcut = oShell.ExpandEnvironmentStrings("" & args.Item(0) & "") sTarget = args.Item(1) sStartIn = args.Item(2)
WScript.Echo "Shortcut: " & sShortcut WScript.Echo "Target: " & sTarget WScript.Echo "StartIn: " & sStartIn
Output:
Shortcut: C:\ProgramData\Microsoft\Windows\Start Menu\Strategix Programs\Office Programs\Purchase
Target: Order
StartIn: Entry.lnk
Batch part
#echo off
set "office7=C:\ProgramData\Microsoft\Windows\Start Menu\Strategix Programs\Office Programs"
mkdir "%office7%"
cscript "H:\Installation Batch Files\createLink.vbs" "%office7%\Purchase Order Entry.lnk" "\\192.168.0.7\Temp\stock\Porder10.exe" "T:\Stock"
pause
The "correct" way of dealing with quotes is not include them in the value. If later you need them, adding them is easy (look the mkdir command and the arguments), but removing them is not. Without a good reason, do not include them. So, the "correct" way is
set "var=value"
That will assign the value to the variable, take care of problematic characters (all the assignation is inside quotes) and keep possible spaces at the end of the line out of the variable value.
Now, to the vbs part
Dim oShell
Set oShell = CreateObject("WScript.Shell")
Dim args
Set args = WScript.Arguments
Dim sShortcut, sTarget, sStartIn
sShortcut = args.Item(0)
sTarget = args.Item(1)
sStartIn = args.Item(2)
WScript.Echo "Shortcut: " & sShortcut
WScript.Echo "Target: " & sTarget
WScript.Echo "StartIn: " & sStartIn
There is no need for ExpandEnvironmentStrings, this has been done when the batch line was parsed in cmd. %office7% is a reference to the value of the variable, not the name of the variable, and the parser replaces variable reads with variable values.
And for the shortcut creation
With oShell.CreateShortcut( sShortcut )
.TargetPath = sTarget
.WorkingDirectory = sStartIn
.Save
End With

VBS Run cmd.exe output to a variable; not text file

This is what I have so far. It works; outputing the folder path to temp to a text file.
What I really want, is to output the data to a variable. Every example I see online, show how to do this using something like:
set objScriptExec = wshShell.Exec (strCommand)
followed by
strresult = LCase(objScriptExec.StdOut.ReadAll. // code
I want this to run with Run, not Exec, because I want the command prompt windows to be hidden as I will performing many commands with the code below. How can I capture that output to a variable?
Set wsShell = CreateObject("WScript.Shell")
strCommand = "cmd /c echo %temp% > %temp%\test.txt"
wsShell.Run strcommand,0,True
This may be done with the Windows Script Host Exec command. StdOut, StdIn, and StdErr may all be accessed, and ERRORLEVEL is available when the command completes.
Dim strMessage, strScript, strStdErr, strStdOut
Dim oExec, oWshShell, intErrorLevel
Dim ComSpec
Set oWshShell = CreateObject("WScript.Shell")
ComSpec = oWshShell.ExpandEnvironmentStrings("%comspec%")
intErrorLevel = 0
strScript = ComSpec & " /C echo %temp%"
On Error Resume Next
Set oExec = oWshShell.Exec (strScript)
If (Err.Number <> 0) Then
strMessage = "Error: " & Err.Message
intErrorLevel = 1
Else
Do While oExec.Status = 0
Do While Not oExec.StdOut.AtEndOfStream
strStdOut = strStdOut & oExec.StdOut.ReadLine & vbCrLf
Loop
Do While Not oExec.StdErr.AtEndOfStream
strStdErr = strStdErr & oExec.StdErr.ReadLine & vbCrLf
Loop
WScript.Sleep 0
Loop
intErrorLevel = oExec.ExitCode
strMessage = strStdOut & strStdErr & CStr(intErrorLevel)
End If
WScript.Echo (strMessage)
NOTE: Replacing "ReadLine" above with "Read(1)" accomplishes the same thing, but adds an ability to process characters rather than whole lines.
Of course Wscript.Shell would be a lot easier, but, since you want more fine grain control of your session, consider using Win32_Process. Usually, one uses this to control the placement of a new window, but, in your case, you want it hidden, so I set startupInfo.ShowWindow = 0 which means SW_HIDE. The following declares a VBScript function called RunCmd and which will run a command in an invisible window saving the output to a text file and then return the contents of the text file to the caller. As an example, I invoke RunCmd with the HOSTNAME command:
Function RunCmd(strCmd)
Dim wmiService
Set wmiService = GetObject("winmgmts:\\.\root\cimv2")
Dim startupInfo
Set startupInfo = wmiService.Get("Win32_ProcessStartup")
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim cwd
cwd = fso.GetAbsolutePathname(".")
startupInfo.SpawnInstance_
startupInfo.ShowWindow = 0
' startupInfo.X = 50
' startupInfo.y = 50
' startupInfo.XSize = 150
' startupInfo.YSize = 50
' startupInfo.Title = "Hello"
' startupInfo.XCountChars = 36
' startupInfo.YCountChars = 1
Dim objNewProcess
Set objNewProcess = wmiService.Get("Win32_Process")
Dim intPID
Dim errRtn
errRtn = objNewProcess.Create("cmd.exe /c """ & strCmd & """ > out.txt", cwd, startupInfo, intPID)
Dim f
Set f = fso.OpenTextFile("out.txt", 1)
RunCmd = f.ReadAll
f.Close
End Function
MsgBox RunCmd("HOSTNAME")
References:
Create method of the Win32_Process class
Win32_ProcessStartup class

vbScript to execute all files in a dir

I'm trying to write a vbScript that will execute all files in a given directory (will be mostly batch files).
I've tried to modify a script that deletes all files but I'm not able to get it to work.
Here is what I have:
Option Explicit
'===========================================================================
' Scheduled Task - Visual Basic ActiveX Script
'===========================================================================
Call ExecuteDirectory("c:\users\public\documents\schedule\daily")
Function ExecuteDirectory(strPath2Folder)
Dim fso, f, fc, f1, strFiles, intFiles
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
strFiles = ""
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(strPath2Folder)) Then
Set f = fso.GetFolder(strPath2Folder)
Set fc = f.Files
'-- Execute each file in Folder
For Each f1 in fc
strFiles = strFiles & f1.Name & vbCrLf
msgbox strPath2Folder & "\" & strFiles
WshShell.Run Chr(34) & strFiles & Chr(34), 1, true
Next
Set f1 = Nothing
Set fc = Nothing
Set f = Nothing
End If
Set fso = Nothing
End Function
The msgbox line displays the full path and file name that I want to execute, but the run line generates file not found error.
The variable strFiles continually builds up a list of files with line breaks in between. For example, if your folder contains the files "test1.bat" and "test2.bat", you will end up with this:
Iteration 1:
strFiles =
test1.bat
Iteration 1:
strFiles =
test1.bat
test2.bat
I don't think this is what you want to do. If you want to just run each script in order, you should just pass the single script name.
Try changing the inner loop to this:
For Each f1 in fc
Dim fileToRun
fileToRun = strPath2Folder & "\" & f1.Name
WshShell.Run Chr(34) & fileToRun & Chr(34), 1, true
Next
This is a very sloppy approach. If you are needing to execute an entire directory of batch files at one time, then you are not using them correctly. You should only need one batch file or one script an any time. I would begin looking at your whole system for a better approach to whatever it is that you are trying to accomplish.

Resources