Want to use VBScript to run .bat file in a different folder - batch-file

I'm trying to run a .bat file using VBScript. I can get the VBScript to work when executed within the same folder as the .bat, however, I can't figure out how to make it successfully run when outside the folder.
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run "C:\Users\js\Desktop\createIndex\createindex.bat"

Going out on a limb I would suspect that the batch script requires its own parent folder to be the working directory. You can set the working directory accordingly by changing your code to this:
Set shell = CreateObject("WScript.Shell")
shell.CurrentDirectory = "C:\Users\js\Desktop\createIndex"
shell.Run "createindex.bat"
If the above doesn't help you need to provide more information about what should happen and what actually does happen. Running the external command/script in visible mode and without automatically closing CMD usually helps with debugging:
shell.CurrentDirectory = "C:\Users\js\Desktop\createIndex"
shell.Run "cmd /k createindex.bat", 1, True

I've 4 simple scripts for what kind of calls.
call.vbs
call_nowait.vbs
call_nowindow.vbs
call_nowindow_nowait.vbs
All the 4 has these lines of code in the beginning:
ReDim args(WScript.Arguments.Count-1)
For i = 0 To WScript.Arguments.Count-1
If InStr(WScript.Arguments(i), " ") > 0 Then
args(i) = Chr(34) & WScript.Arguments(i) & Chr(34)
ElseIf WScript.Arguments(i) = "" Then
args(i) = Chr(34) & WScript.Arguments(i) & Chr(34)
Else
args(i) = WScript.Arguments(i)
End If
Next
Set objShell = WScript.CreateObject("WScript.Shell")
' MsgBox Join(args, " ")
Plus the last line is different in all 4 scripts:
call.vbs
objShell.Run Join(args, " "), 1, True
call_nowait.vbs
objShell.Run Join(args, " "), 1, False
call_nowindow.vbs
objShell.Run Join(args, " "), 0, True
call_nowindow_nowait.vbs
objShell.Run Join(args, " "), 0, False
For example, the entire command line for the call_nowindow.vbs script looks like this:
call_nowindow.vbs "C:\Users\js\Desktop\createIndex\createindex.bat"
By the way, you can run anything by these scripts, not only just batch files.
This one will create an instance of notepad.exe with out window:
call_nowindow.vbs notepad
This one will create cmd console with current date and time, and leave the window open:
call_nowait.vbs cmd /k echo.%DATE% %TIME%

Use this script to set the directory to the current working directory of your script. That way whenever the script changes directories it will look for it there instead of hard rooting it to a specific directory.
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
This will make any files that it is looking for in that directory available to the script.
Example : If the file were on the current users desktop.
C:\Users\[Username]\desktop\myfile.vbs
Will become:
scriptdir\myfile.vbs
and if you moved it to a subfolder "subfolder" it would remain
scriptdir\myfile.vbs
even if the script location is different. The "scriptdir" is a placeholder for the folder the active script is running from.

Related

Passing a windows path to a vbs script which then runs a batch file

I'm trying to run a batch file hidden. I have read many threads here but I still can't get it working. Win7 - I have created a new toolbar in the taskbar that shows me all .enc files in a specific folder. I want to click to select one of those filenames and have it sent to the vbs script that will run a batch file hidden with that filename as the first argument for the batch file. I am using total commander and have set up a file association of the below for .enc files -
hidebat.vbs %1
That is supposed to take the filename I selected and send it to the script.
This is the script hidebat.vbs -
CreateObject("Wscript.Shell").Run "G:\test\clipTest.bat" WScript.Arguments(0), 0, True
That is from another thread on this topic to run batch files hidden but with my addition of the WScript.Arguments(0) part. Supposedly that grabs the first argument to the vbs script.
When I try this out I get a window stating that the filename I selected is not a valid win32 application. Is it obvious what's wrong?
If it all could be done within the vbs script, all the better. I'm only doing two things in the batch file -
1. echo|set /p=%1|clip (echoing that filename to the clipboard)
2. start "" "g:\test\Process.lnk" (running this shortcut)
You forgot the & as well as a space between the script and your argument.
Try this:
CreateObject("Wscript.Shell").Run "G:\test\clipTest.bat " & WScript.Arguments(0), 0, True
Try the following. Chr(34) resolves to a quote, in case your paths contain spaces:
CreateObject("Wscript.Shell").Run chr(34) & "G:\test\clipTest.bat" & chr(34) & " " & chr(34) & WScript.Arguments(0) & chr(34), 0, True
I had to change my file association line to -
wscript "g:\path\to\hidebat.vbs" "%1"
Now it works, thanks!

Run a .bat file from a vbs without having to specify its drive C:

I am asking you guys how to run a .bat file from a .vbs without having to specify its containing drive C:. I want to try to make some sort of installation and I did a fake loading or installing screen that a .bat file opens up and does its mini animation from .vbs. The problem about this is when I send this .vbs with the .bat it always says that an error occurred; and this is what I found:
CreateObject("WScript.Shell").Run("""C:\Users\Name\Desktop\Thingy.bat""")
The problem with this script is that the person I send it to will also need the same name as I and in C:. How can I change this script, or is it impossible?
Next commented code snippet should do the job (most statements and commands are itemized for the sake of comprehensibility):
option explicit
On Error GoTo 0
' declare variables
Dim WshShell, sUserProfile, strCommand, fso
' assign all object references to appropriate variables
Set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
' get an environment variable's expanded value
sUserProfile = WshShell.ExpandEnvironmentStrings("%UserProfile%")
' build command to run
strCommand = """" _
& fso.BuildPath( fso.BuildPath( sUserProfile, "Desktop"), "Thingy.bat") & """"
Wscript.Echo "(debug) command to run" & vbNewLine & strCommand
WshShell.Run strCommand
If the batch file is always on the desktop,you should use %userprofile% like this way :
CreateObject("WScript.Shell").Run(chr(34) & "%userprofile%\Desktop\Thingy.bat" & chr(34))
Or something like that when the batch file and the vbscript file are both in the same folder :
Set FSO = CreateObject("Scripting.FileSystemObject")
scriptPath = FSO.GetParentFolderName(wscript.ScriptFullName)
wscript.echo scriptPath
MyBatchFile = chr(34) & scriptPath & "\Thingy.bat" & chr(34)
wscript.echo MyBatchFile
CreateObject("WScript.Shell").Run(MyBatchFile)

How to set process priority when starting an executable from a batch file in Windows without launching terminal

I have a .bat file [1] starting from a .vbs script [2] which only launches without launching a terminal if I don't include 'Start /low' in the .bat file.
The 'Start /low' part of the .bat file launches the command with the right (low) priority set, but it launches in a terminal, which I don't want.
I'm only able to launch the desired command in the background without a terminal if I don't set the priority in the .bat file. In which case the final .exe that launches slows my computer down, which is why I want to set its priority to 'low'.
I tried this [3], but it gives me an error when I run it [4].
Would someone kindly tell me how to make the executable start with low priority without launching a terminal window?
[1]
Start /low C:/dataserv-client/dataserv-client.exe --store_path=C:\Users\Chris\StorjData --max_size=800.0GB farm
[2]
Dim WinScriptHost
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\Users\Chris\Scripts\start_dataserv-client.bat" & Chr(34), 0
Set WinScriptHost = Nothing
[3]
Dim WinScriptHost
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Start /low C:/dataserv-client/dataserv-client.exe --store_path=C:\Users\Chris\StorjData --max_size=800.0GB farm" & Chr(34), 0
Set WinScriptHost = Nothing
4
The code in [3] didn't work because 1) the closing quote added with chr(34) was in the wrong place - only the executable should be quoted this way, not the entire command line and 2) start isn't a standalone utility which can be executed directly by .Run, it's a command of the command processor cmd (easily checked by running where start in the command prompt console).
CreateObject("WScript.Shell").Run "cmd /c Start /low " & chr(34) & chr(34) & " " & _
chr(34) & "C:\dataserv-client\dataserv-client.exe" & chr(34) & _
" --store_path=C:\Users\Chris\StorjData --max_size=800.0GB farm", 0
which executes cmd /c start /low "" "C:\dataserv-client\dataserv-client.exe" ......... - the first "" is for the title parameter of start so that cmd won't confuse it with the quoted exe path.

Make VBScript check for a file with a certain word in it's file name and then find and delete that file

I was wondering if there is a way to make it so my vbs script can check for and delete any files with a certain word in it's name. This is what I have so far:
x=MsgBox ("Searching for any infected files...",64,"Search")
DIM filesys
Set filesys = CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("C:\Documents and Settings\Name\Desktop\example.txt") Then
WScript.Sleep 1500
x=MsgBox ("Warning! A infected file was found!",48,"Warning")
filesys.DeleteFile "C:\Documents and Settings\Name\Desktop\example.txt"
x=MsgBox ("File was deleted!",48,"File Deleted")
WScript.Sleep 1000
x=MsgBox ("This Computer is now clean!",64,"Hooray!")
Else
WScript.Sleep 500
x=MsgBox ("File not found! This Computer is clean!",64,"Hooray!")
End If
Is there also a way to make the username/file path work on any computer? I know it is
"C:\Documents and Settings\%username%\Desktop\example.txt"
in batch, but is there something like that in vbscript? Is there also a way to delete files with ANY extension that have 'example' in the name as well? For example:
filesys.DeleteFile "C:\Documents and Settings\Name\Desktop\example.anyextension"
Thanks so much! I hope you don't mind my huge amount of questions, I am just starting to code with VBS/VBScript and really appreciate your help! :)
ExpandEnvironmentStrings method returns an environment variable's expanded value. Environment variable names, which must be enclosed between % characters, are not case-sensitive:
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "Current user name: " _
& WshShell.ExpandEnvironmentStrings("%USERNAME%")
WScript.Echo "Desktop folder: " _
& WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
All next code snippets pasted here unchanged from linked sources. Could become a starting point for any VBScript beginner. Inspire yourself at next huge script repository: Script resources for IT professionals.
Stolen from Search for Files Using a Wildcard Query. Uses the Like keyword to search for all files on a computer that contain a tilde (~). However, read CIM_DataFile class at MSDN:
The following VBS code sample describes how to perform a standard
wildcard search on a datafile. Note that the backslash delimiters must
be escaped with another backslash (\\). Also, when using
"CIM_DataFile.FileName" in the WHERE clause, the WMIPRVSE
process will scan all directories on any available storage device.
This may take some time, especially if you have mapped remote shares,
and can trigger antivirus warnings.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_DataFile where FileName Like '%~%'")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
Here's a smarter and faster solution with comprehensive comments: How Can I Delete Specific Files in a Specific Folder? at Hey, Scripting Guy! blog (next to ten years old):
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFileList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='T:\Act'} Where " _
& "ResultClass = CIM_DataFile")
For Each objFile In colFileList
If InStr(objFile.FileName, "current") Then
objFile.Delete
End If
Next
Of course, like most WMI scripts, this one can also be run against a remote computer.

How can i make a hidden window with bat files ?

i need to make a batch file that have a hidden process and window for the users
i have already my batches file and want to make one of them hidden
vbs can't make that or any programming language ?
here you can find multiple ways to do this : https://stackoverflow.com/questions/28284876/what-are-the-different-ways-to-start-a-hidden-process-with-batch-file-and-what-a
Probably the best is with Win32_ProcessStartup as it returns also the pid of the started process.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\file.bat" & Chr(34), 0
Set WshShell = Nothing
with Vbs and call the bat file this is the way
Use the start command:
start /b my.bat
Refer to: https://technet.microsoft.com/en-us/library/cc770297(v=ws.11).aspx

Resources