vbScript to execute all files in a dir - vbscript

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.

Related

VBS script to rename files using the pathname

i am new to VBS scripting and I have done few stuff with Excel VBA before. Now I have a script which renames single files with the pathname of the files (truncated to 4 letter each))see below. It is some script which I modified a bit to fit my purpose. However, I would like to automatize the file rename process and rename all files in a folder and its subfolders in the same way the scipt works for single files. Can anybody help me with this question?
Set Shell = WScript.CreateObject("WScript.Shell")
Set Parameter = WScript.Arguments
For i = 0 To Parameter.Count - 1
Set fso = CreateObject("Scripting.FileSystemObject")
findFolder = fso.GetParentFolderName(Parameter(i))
PathName = fso.GetAbsolutePathName(Parameter(i))
FileExt = fso.GetExtensionName(Parameter(i))
Search = ":"
findFolder2= Right(PathName, Len(PathName) - InStrRev(PathName, Search))
arr = Split(findFolder2, "\")
For j=0 To UBound(arr)-1
arr(j) = ucase(Left(arr(j), 4))
Next
joined = Join(arr, "%")
prefix = right(joined, len(joined)-1)
fso.MoveFile Parameter(i), findFolder + "\" + prefix
next
Hoping that I can get some useful ideas.
Herbie
Walking a tree requires recursion, a function calling itself for each level.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.DateLastModified
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
From Help on how to run another file.
Set Shell = WScript.CreateObject("WScript.Shell")
shell.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
So outside the loop,
Set Shell = WScript.CreateObject("WScript.Shell")
And in the loop
shell.Run("wscript Yourscript.vbs thing.name, 1, True)
Also the VBS help file has recently been taken down at MS web site. It is available on my skydrive at https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw It's called script56.chm.

How to run windows executable and delete files from sub folders

I need a quick script do two parts.
Run a windows executable
Delete files within a folder and subfolders (*.jpg, *.img).
The first part of the below script works (running the executable) but I am getting stuck on part 2. I get
Cannot use parentheses when calling a sub
The error is on the line with the RecursiveDelete call. I actually cut and pasted that code from another SO question. I have googled the error but still don't understand.
Can anybody know how to get this script working?
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Users\acer\Desktop\CT\process.exe" & Chr(34), 0
Set WshShell = Nothing
Dim PicArray(2)
Dim p
PicArray(1) = "*.jpg"
PicArray(2) = "*.img"
For p = 1 To 2
RecursiveDelete ("D:\pictures", PicArray(p))
Next p
Private Sub RecursiveDelete(ByVal Path As String, ByVal Filter As String)
Dim s
For Each s In System.IO.Directory.GetDirectories(Path)
try
RecursiveDelete(s, Filter)
catch dirEx as exception
debug.writeline("Cannot Access " & s & " : " & dirEx.message
end try
Next
For Each s In System.IO.Directory.GetFiles(Path, Filter)
try
System.IO.File.Delete(s)
catch ex as exception
debug.writeline("Cannot delete " & s & " : " & ex.message)
end try
Next
End Sub
Update: Revised answer from Hackoo that works great.
Option Explicit
Dim fso,RootFolder, wshShell
set fso = CreateObject("Scripting.FileSystemObject")
RootFolder = "D:\pictures"
Set RootFolder = fso.GetFolder(RootFolder)
Call RecursiveDelete(RootFolder)
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\process.exe" & Chr(34), 0
Set WshShell = Nothing
'*****************************************************************************
Function RecursiveDelete(Folder)
Dim File,MyFile,Ext,i,SubFolder
Set Folder = fso.GetFolder(Folder)
For each File in Folder.Files
Set MyFile = fso.GetFile(File)
Ext = Array("iMG","JPG")
For i = LBound(Ext) To UBound(Ext)
If LCase(fso.GetExtensionName(File.name)) = LCase(Ext(i)) Then
MyFile.Delete()
Exit For
end if
Next
Next
For each SubFolder in Folder.SubFolders
Call RecursiveDelete(SubFolder)
Next
End Function
'*****************************************************************************
Try like this way :
Option Explicit
Dim fso,RootFolder
set fso = CreateObject("Scripting.FileSystemObject")
RootFolder = "D:\pictures"
Set RootFolder = fso.GetFolder(RootFolder)
Call RecursiveDelete(RootFolder)
Msgbox "Pictures Cleaned !",vbInformation,"Pictures Cleaned !"
'*****************************************************************************
Function RecursiveDelete(Folder)
Dim File,MyFile,Ext,i,SubFolder
Set Folder = fso.GetFolder(Folder)
For each File in Folder.Files
Set MyFile = fso.GetFile(File)
Ext = Array("jpg","img")
For i = LBound(Ext) To UBound(Ext)
If LCase(fso.GetExtensionName(File.name)) = LCase(Ext(i)) Then
MyFile.Delete()
Exit For
end if
Next
Next
For each SubFolder in Folder.SubFolders
Call RecursiveDelete(SubFolder)
Next
End Function
'*****************************************************************************
Instead of passing the array item into RecursiveDelete, obtain the contents of the array item into a variable within the loop, and pass that variable instead.
Code would be similar to this- did not have a chance to test syntax.
For p = 1 To 2
Dim PicItem
PicItem = PicArray(p)
RecursiveDelete ("D:\pictures", PicItem )
Next p

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

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>

How to redirect output from EXE to TXT file using VBScript?

The requirement is to execute a certain script on multiple workstations using a tool such as Microsoft SCCM.
This script is required to execute the EXE 'C:\ugs\nx5\UGII\env_print.exe' on every workstation. This is to be done twice using the following parameters :
C:\ugs\nx5\UGII\env_print.exe -m
C:\ugs\nx5\UGII\env_print.exe -n
The script must be designed such that the output from the above mentioned should be stored at someplace on the workstation, from where SCCM could read the values.
To achieve this requirement, I wrote the following VBscript :
--------------------------------------------------------------------------------------------
On Error Resume Next
Const HKEY_LOCAL_MACHINE = &H80000002
Dim WshShell, fso, file, objRegistry, strKeyPath, strSysDrive, outputFile, strTEMP, file2, oTxtFile, oTxtFile2
Dim ComExec, strSysRoot, strComputer, outputFile2, EXEpath, ComExec2, return, return2, text, text2, CMDPath
strComputer = "."
Set WshShell = Wscript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
strSysDrive = WshShell.ExpandEnvironmentStrings("%SystemDrive%")
strSysRoot = WshShell.ExpandEnvironmentStrings("%SystemRoot%")
EXEpath = strSysDrive & "\ugs\nx5\UGII\env_print.exe"
CMDPath = strSysRoot & "\system32\cmd.exe"
'-----------------------SET TXT FILE LOCATION-----------------------
outputFile = strSysDrive & "\env_print_m.txt"
outputFile2 = strSysDrive & "\env_print_n.txt"
'-----------------------CREATE TEXT FILES-----------------------
Set oTxtFile = fso.CreateTextFile(outputFile)
Set oTxtFile2 = fso.CreateTextFile(outputFile2)
'-------COMMAND TO EXECUTE AND REDIRECT OUTPUT TO TXT FILE-------
ComExec = CMDPath & " /c " & EXEpath & " -m >> " & outputFile
ComExec2 = CMDPath & " /c " & EXEpath & " -n >> " & outputFile2
'-----------------------EXEUTE COMMANDS-----------------------
return = WshShell.Run(ComExec, 0, true)
return2 = WshShell.Run(ComExec2, 0, true)
'-----------------------READ OUTPUT FROM TXT FILES-----------------------
Set file = fso.OpenTextFile(outputFile, 1)
text = file.ReadAll
file.Close
Set file2 = fso.OpenTextFile(outputFile2, 1)
text2 = file2.ReadAll
file.Close
'-----------------------WRITE OUTPUT VALUES TO REGISTRY STRING VALUES-----------------------
strKeyPath = "SOFTWARE\env_print_Ver"
objRegistry.CreateKey HKEY_LOCAL_MACHINE, strKeyPath
WshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_m", text, "REG_SZ"
WshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_n", text2, "REG_SZ"
'-----------------------DELETE TXT FILES-----------------------
fso.DeleteFile outputFile
fso.DeleteFile outputFile2
--------------------------------------------------------------------------------------------
This script executes the EXE with the required parameters and stores the output to 2 different TXT files(env_print_m.txt and env_print_n.txt).
Then reads these string values from the text files and stores them as registry string values at the following locations, so that it could be read by SCCM.
HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_m
HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_n
However, when this script is executed on workstations running Windows XP, the outputs aren't redirected to the TXT files. No errors are displayed either.
I am at my wits end. Please help.
As your first output file is not named/specified outputFile, change
Set file = fso.OpenTextFile("outputFile", 1)
to
Set file = fso.OpenTextFile(outputFile, 1)
(Same for the second one)
Trying to access a file wrongly named should abort your script with an error message. You switched of this feature by an EVIL global "On Error Resume Next". Get rid of it and see if "outputs aren't redirected' is explained by an error message.
Added wrt comment:
If something like
WshShell.Run ComExec, 0, true
'does not work' you should:
call .Run as a function and check the return value
echo the command (ComExec) and try to execute exactly this command from a console
switch /c to /k and look
sacrify a goat and think about permissions
Oh, I forgot:
manually delete the output files and check if they are created but get no content - then reconder the .exe

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

Resources