Wednesday June 17, 2009 12:05
Force Command-Line for VBScripts
Say you have a script—like the previous CIM Repository Listing script—that outputs hundreds of rows of text via WScript.Echo. On the command line, this is fine; the text will go scrolling by, and can be piped to the more command or grep (yes, really), or logged to a file. But if you make the mistake of executing a script like this by double-clicking, you’ll get modal popup messages that prevent the rest of the script from running until you hit “OK” for each line.
You could change the default scripting environment to always be the command line:
CScript //H:CScript //NoLogo //S
But then you have to treat the GUI-based scripts differently, and launch them from the command line with wscript. Oh, bother.
It’s always been possible to just go ahead and launch vbscripts from the command line with the cscript command, but having to open a command prompt and type out the path to the script every time is a pain. Why not have the script auto-detect how it was launched, and if it wasn’t launched from the command line, relaunch itself correctly? Well, Tek-Tips user tsuji has figured out how to do it.
By including this subroutine in your VBScript and putting a call to it at the top of the script, it will do just that.
The edits to this script from tsuji’s version are that instead of keeping the command window open after execution with the “/k” switch, I continue to use the “/c” (close command after completion) but chain the “pause” command at the end of the command. This is a little-known (in the DOS/Windows world, anyway) way of doing multiple things at once:
command1 && command2On *NIX, this will execute command2 after command1 completes, if it completes successfully (return code 0). On Windows, however, command2 will always be run, no matter the outcome of command1.
Sub force_cmdline Dim args : args="" Dim i, wshshell If right(lCase(wscript.fullname),11)= "wscript.exe" then For i=0 to wscript.arguments.count-1 args = args & wscript.arguments(i) & " " Next Set wshshell = createobject("wscript.shell") wshshell.Run wshshell.ExpandEnvironmentStrings("%comspec%") & " /c cscript.exe //nologo """ & wscript.scriptfullname & """" & args & " && pause" set wshshell = Nothing WScript.Quit End If End Sub
- Category: MidSOUTH
- Comments Off