Using the ShellExec Object to Your Advantage
Good day everyone! Today, I have for you a short article on using the
WshScriptExec object to help you write quality VBscripts while still being able to make calls to external executables. The WshScriptExec object cannot be directly instantiated, but rather is captured when executing a process. By setting a variable equal to the output of the WshShell.Exec method, you can grab an instance of the WshScriptExec object. Once you "get" this object, you are able to manipulate the running process by sending commands to it, or by looking at the console output of the program. Let's run through a quick example of how we can use the WshScriptExec object to make a better script.
Sample ScriptPurpose: We will create a sample script to back up some plain-text log files (IIS logs for example), compress them into an archive folder using
7-zip, and then delete the temporary copy of the log files we create. Yes, I know we could back them up directly from the source, but it's always good to have a temporary working copy and clean up afterwards.
Strategy: 1) Using the FileSystemObject (FSO), copy the log files from a network path to the local machine. 2) Use the WshShell.Exec method to execute 7-zip with proper arguments. 3) We will use the StdOut property of the WshScriptExec object to determine when 7-zip has completed. 4) Use existing FSO to remove the (now compressed) log files.
'Create FSO and Shell object
set fso = CreateObject("Scripting.FileSystemObject")
set shell = CreateObject("Wscript.Shell")
'Establish local and remote working directories
remotedir = "\\fileserver01\logs"
localdir = shell.SpecialFolders("MyDocuments") & "\logs\"
'Function to copy log files from remotedir to localdir
function copyFiles()
'Use CopyFile method of FSO to copy files
fso.copyfile remotedir & "\*.log", localdir
end function
'Function to compress files with 7-zip
function compressFiles()
'use WshShell.Exec method to execute 7-zip command. Double-double quotes are there to encapsulate file paths with spaces--IMPORTANT
'Capture return value (the WshScriptExec object we want) in variable output
set output = shell.exec "7za a """ & localdir & "archive"" """ & localdir & "*.log"""
'Don't proceed with rest of script (log clean-up) until 7-zip is done executing. 7-zip will normally write "Everything is OK" to the console when completed successfully
while not (instr(output.stdout.readall, "Everything") <> 0)
wscript.sleep 100
wend
end function
function cleanUp()
fso.deletefile localdir & "*.log"
end function
So there you have it. By using the StdOut property, we can test the console output to see if 7-zip executed properly. It's missing a main function to make calls to the other functions, but ... the concept is there, and 7-zip compression is awesome.