Using the windows file dialog box in VBScript to provide file selections and populate script options
Sometimes the command line is great for getting a script running and doing the task a script was intended to do, however, sometimes you simply don’t want to add the overhead of opening a command prompt, navigating to the directory where your script is located, and then remembering the command line options you entered into the script to make it run the last time. Then sometimes you just don’t want to hard code the file name into your script because you don’t want to have to change it every time.
In fact, sometimes your script is intended for users who might not even know how to run a script from the command line! Wouldn’t it be great if you could just have windows display a dialog box to prompt the user for a file to chose as a argument for your script?
Well, you CAN! The following script is a sample of what you can do with the Windows Common Dialog box to enable the user to more easily utilize your scripts– all without knowing about the command line!
There are a few key pieces of the script I want to call out before we dig in and start running the code though. First, the object that preforms the magic here is UserAccounts.CommonDialog, the filter options on the dialog in the drop down to select the file types to display in the browser dialog is the line with .Filter property in it, The initial Directory the dialog uses is specified in the .InitialDirectory Property, and finally the default selection of that drop down is specified in the .FilterIndex Property. Take a look at the code and see how easy it is.
Dim ObjFSO, InitFSO
‘ create an instance of the File Browser
Set ObjFSO = CreateObject(“UserAccounts.CommonDialog”)
‘setup the File Browser specifics
ObjFSO.Filter = “VBScripts|*.vbs|Text Files|*.txt|All Files|*.*”
ObjFSO.FilterIndex = 3
ObjFSO.InitialDir = “c:\”
‘ show the file browser and return the selection (or lack of) to InitFSO
InitFSO = ObjFSO.ShowOpen
If InitFSO = False Then
Wscript.Echo “Script Error: Please select a file!”
WScript.Echo “You selected the file: ” & ObjFSO.FileName