programming4us
programming4us
DESKTOP

Windows Vista : Scripting and Automation - Object References (part 2) - How to Use the Network, How to Control Internet Explorer, How to Use Command-Line Parameters

9/21/2012 3:42:30 AM

4. How to Create Windows Shortcuts and Internet Shortcuts

Include the following subroutine in your script to allow easy creation of Internet Shortcuts (*.url) and Windows Shortcuts (*.lnk):

Sub Shortcut(LinkFile, CommandLine)
  Set WshShell = WScript.CreateObject("WScript.Shell")
  If LCase(Right(LinkFile, 4)) <> ".lnk" And _
         LCase(Right(LinkFile, 4)) <>".url" Then _
         LinkFile = LinkFile & ".LNK"
  Set ShortcutHandle = WshShell.CreateShortcut(LinkFile)
  ShortcutHandle.TargetPath = CommandLine
  ShortcutHandle.Save
End Sub

To create a shortcut to a program or file, use the following statement:

Call Shortcut("C:\Users\username\AppData\Roaming\Microsoft\Windows\
                      SendTo\Notepad.lnk", _"Notepad.exe")

To create a shortcut to an Internet address:

Call Shortcut("D:\Prjects\Important\Annoyances.url", _
              "http://www.annoyances.org/")

If the first parameter, LinkFile, ends in .lnk (case doesn't matter), the Shortcut subroutine automatically creates a standard Windows shortcut; if LinkFile ends in .url, however, an Internet Shortcut file is created. Note the If...Then structure in the routine, which automatically adds the .lnk filename extension if no proper extension is found.

The LCase function, which transforms the contents of any variable to lowercase, is vital here, as it completely compensates for .URL, .url, .Url, and any other case mismatches in the specified filename.


If you specify a nonexistent folder in the path for the new shortcut file, an "Unspecified Error" will occur. 

5. How to Use the Network

WSH has a few limited networking functions built in that can be used for mapping network drives and connecting to network printers. For advanced network functionality (such as communication and network traffic monitoring), check out PowerShell.

The following routines provide access to some of the more useful network-related functions in VBScript.

The following function checks a given drive letter to see whether it has already been mapped. It returns True (−1) if the drive letter has been mapped, False (0) if it hasn't:

Function AlreadyMapped(DriveLetter)
  Set WshShell = WScript.CreateObject("WScript.Shell")
  Set WshNetwork = WScript.CreateObject("WScript.Network")
  Set AllDrives = WshNetwork.EnumNetworkDrives(  )

  If Left(DriveLetter,1) <> ":" then DriveLetter = DriveLetter & ":"
  ConnectedFlag = False
  For i = 0 To AllDrives.Count - 1 Step 2
    If AllDrives.Item(i) = UCase(DriveLetter) Then ConnectedFlag = True
  Next

  AlreadyMapped = ConnectedFlag
End Function

This subroutine maps a drive letter to any valid remote path:

Sub MapNetDrive(DriveLetter, RemotePath)
  Set WshShell = WScript.CreateObject("WScript.Shell")
  Set WshNetwork = WScript.CreateObject("WScript.Network")
  WShNetwork.MapNetworkDrive DriveLetter, RemotePath
End Sub

This subroutine maps an unused printer port (e.g., LPT3) to any valid remote network printer:

Sub MapNetPrinter(Port, RemotePath)
  Set WshShell = WScript.CreateObject("WScript.Shell")
  Set WshNetwork = WScript.CreateObject("WScript.Network")
  WshNetwork.AddPrinterConnection Port, RemotePath
End Sub

These subroutines remove the mapping for previously mapped drive letters and network printers, respectively:

Sub UnMapNetDrive(DriveLetter)
  Set WshShell = WScript.CreateObject("WScript.Shell")
  Set WshNetwork = WScript.CreateObject("WScript.Network")
  WShNetwork.RemoveNetworkDrive DriveLetter
End Sub

Sub UnMapNetPrinter(Port)
  Set WshShell = WScript.CreateObject("WScript.Shell")
  Set WshNetwork = WScript.CreateObject("WScript.Network")
  WshNetwork.RemovePrinterConnection Port
End Sub

This next script serves as an example for these subroutines. It's used to map a network drive if it's not already mapped, or to disconnect a currently mapped drive. The AlreadyMapped, MapNetDrive, and UnMapNetDrive routines are required.

DriveLetter = "N:"
RemotePath = "\\server\c"

If AlreadyMapped(DriveLetter) then
  Call UnMapNetDrive(DriveLetter)
  Msgbox "Drive " & DriveLetter & " disconnected."
Else
  Call MapNetDrive(DriveLetter, RemotePath)
  Msgbox "Drive " & DriveLetter & " connected."
End if

This script requires no user interaction once it has been executed and displays only a single confirmation message when it's done. The first two lines contain the drive letter and network path to be mapped together. Then, the AlreadyMapped function is used to determine whether the drive mapping already exists. The script then maps or disconnects the drive, depending on what's needed; it's a quick and easy toggle that Windows itself just doesn't provide.

6. How to Control Internet Explorer

Because VBScript owes its existence, in part, to Internet Explorer (IE), it seems only fair that there would be some integration between WSH and IE. The key is the IE object and the properties and methods associated with it.

Note that the code in this section is not presented as a subroutine, mostly because all of the subsequent statements that reference the IEObject object (such as IEObject.Document.Write) would fail if the initial Set statement was isolated in its own routine.

Begin with the following lines in your script, which start the IE application, initialize an object to reference, and open a blank IE window:

Set IEObject = CreateObject("InternetExplorer.Application")
If Err.number <> 0 Then
  MsgBox "There was a problem starting Internet Explorer."
  wScript.Quit
End If
IEObject.Left = 75
IEObject.Top = 75
IEObject.Width = 400
IEObject.Height = 300
IEObject.Menubar = 0
IEObject.Toolbar = 0
IEObject.Navigate "About:Blank"
IEObject.Visible=1
Do while IEObject.Busy
  Rem—wait for window to open—
Loop

Note the error checking at the beginning, which quits if there's a problem loading IE. The subsequent commands customize the window to our needs; the Left, Top, Width, and Height properties are all in pixels; for the MenuBar and Toolbar properties, 0 means hidden and 1 means visible. Lastly, the Navigate property specifies the URL to load; in this case, specify "About:Blank" to show a blank page.

Once the IEObject.Visible=1 command is issued, the window appears, and the real fun begins. (OK, perhaps "fun" is too strong of a word.) The following lines send HTML code to the active IE window, and form a simple web page:

IEObject.Document.Write "<html>"
IEObject.Document.Write "<h1>Hello World</h1>"
IEObject.Document.Write "<p>"
IEObject.Document.Write "<i>Aren't we sick of that phrase yet?</i>"
IEObject.Document.Write "</html>"

This has nearly limitless possibilities, not the least of which is a more elegant way to display information than the MsgBox command, a much more sophisticated way of gathering information than the InputBox command (using fill-out forms), and a way to display an ongoing log of a script's activities without interrupting script flow. To clear the page at any time, simply issue another IEObject.Navigate "About:Blank" command.

Note that the IE window stays open after the script completes; use the IEObject.Quit command to close the window during script execution.

7. How to Use Command-Line Parameters

A command-line parameter is a bit of text specified after the filename of a script when it is executed from a Command Prompt (see the following examples). This function converts a single command-line parameter into a variable:

Function CommandLine(Number)
  Set Arguments = WScript.Arguments
  If Number <= Arguments.Count Then
    CommandLine = Arguments(Number - 1)
  Else
    CommandLine = ""
  End If
End Function

For example, to display the second command-line parameter passed to a script, issue the following statement:

MsgBox CommandLine(2)

Although the command line may seem to be an antiquated concept, it's still very much a part of Windows. When you double-click on a .vbs file, for example, Windows actually executes the following command:

wscript.exefilename.vbs

where filename.vbs (the file that was double-clicked) is the command-line parameter for wscript.exe, telling it which script to run.  Scripts also accept command-line parameters, which are entered like this:

wscript.exe filename.vbsparam1 param2

The two additional parameters (you can have as many as you like), param1 and param2, are both passed to the script as command-line parameters, and can be retrieved during runtime by referencing CommandLine(1) and CommandLine(2), respectively.

One of the most common uses of command-line parameters in scripts is to accept filenames, and there are two circumstances when this is most useful:

  • Drag one or more items onto the script file icon. Note that this didn't work in some earlier versions of Windows, as scripts were considered to be documents instead of programs.

  • Place the script in your Send To folder. Then, right-click one or more items in Explorer, select Send To, and then select the name of the script. You can also place a shortcut to the script in your Send To folder, which eliminates the .vbs filename extension that would otherwise appear in Explorer's Send To menu.

In either case, when Windows executes the script, the names of the input file(s) are accessible as command-line parameters, one for each filename. The following example script displays the names of all the files and folders drag-dropped on the script icon:

Report = ""
Set Arguments = WScript.Arguments
For i = 1 to Arguments.Count
  Report = Report + Arguments(i - 1) + vbCrLf
Next
Msgbox Report

The script starts off by clearing the Report variable, and then borrows some code from the CommandLine function listed earlier[18] to initialize the Arguments object and determine the number of dropped files. Next, a For...Next structure runs through the arguments, adding each one to the Report variable, followed by a linefeed (using vbCrLf, a handy built-in constant containing carriage-return and linefeed characters). Note that the Arguments array is zero-based (the first item is Arguments(0), the second is Arguments(1), and so on), so the (i - 1) part is needed to compensate. Lastly, a Msgbox command is used to display the list of dropped files.

[18] * It's actually possible to use the CommandLine function here instead, but doing so would make the script more cumbersome. And exactly who are you going to impress with a cumbersome script?

Other  
  •  Windows Vista : Build a VBScript Script
  •  5 New Lenovo Laptops Using Ivy Bridge Chip
  •  Asus K45VM – Affordable Good-Performance Laptop
  •   Installing or Upgrading to Windows 7 : Installing Windows 7 on a Mac
  •   Installing or Upgrading to Windows 7 : Performing a Clean Install with an Upgrade Version of Windows 7, Delaying Product Activation
  •   Installing or Upgrading to Windows 7 : Upgrading from One Windows 7 Version to Another with Windows Anytime
  •  Windows Server 2008 : Manipulating Services with wmic
  •  Windows Server 2008 : Stopping and Starting Services with the net Command, Manipulating Services with sc
  •  Windows Server 2008 and Windows Vista : Altering Default GPO Processing and Inheritance (part 2) - Security Filtering, WMI Filters, Group Policy Preferences
  •  Windows Server 2008 and Windows Vista : Altering Default GPO Processing and Inheritance (part 1) - Block Policy Inheritance, Enforce
  •  
    video
     
    Video tutorials
    - How To Install Windows 8

    - How To Install Windows Server 2012

    - How To Install Windows Server 2012 On VirtualBox

    - How To Disable Windows 8 Metro UI

    - How To Install Windows Store Apps From Windows 8 Classic Desktop

    - How To Disable Windows Update in Windows 8

    - How To Disable Windows 8 Metro UI

    - How To Add Widgets To Windows 8 Lock Screen

    - How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010
    programming4us programming4us
    programming4us
     
     
    programming4us