While I normally make posts related to web development, I may occasionally post something that isn't used in web development, but still has some kind of relationship (normally the underlying technology used) - for example: VBScript - Set Homepage (MSIE) / Add Notepad to Send To.
In this case, it is VB Scripting and is an example of how to perform several common tasks (related to printers and drives) that network/server administrators may want to do, through a simple script (could be via login script, or executed directly on the client) rather than using the Windows GUI. It also demonstrates how to do basic error handling. Just take the following code (tweak as needed) and paste it in a script file (e.g. login.vbs). Only been tested in Windows XP (for Windows 98, you have to also define the driver name as a second parameter for
AddWindowsPrinterConnection, it should work as is in Windows 2000).
Option Explicit Dim WSHNetwork Dim WSHShell On Error Resume Next Set WSHNetwork = CreateObject("WScript.Network") Set WSHShell = CreateObject("WScript.Shell") rem Add a printer WSHNetwork.AddWindowsPrinterConnection "\\HOSTNAME\PrinterShareName" HandleError "Could Not Add Printer" rem Set this as the default printer WSHNetwork.SetDefaultPrinter "\\HOSTNAME\PrinterShareName" HandleError "Could Not Set As Default Printer" rem Remove an existing printer WSHNetwork.RemovePrinterConnection "\\HOSTNAME\RemovePrinterShareName" HandleError "Could Not Remove Printer / Printer Already Removed" rem Map a drive WSHNetwork.MapNetworkDrive "L:", "\\HOSTNAME\ShareName" HandleError "Could Not Map Drive" rem Remove a drive WSHNetwork.RemoveNetworkDrive "M:" HandleError "Could Not Remove Mapped Drive" Function HandleError(Title) If Err.Number <> 0 Then rem Add to event log. First parameter can be: rem 0 (SUCCESS), 1 (ERROR), 2 (WARNING) rem 4 (INFORMATION), 8 (AUDIT_SUCCESS), 16 (AUDIT_FAILURE) WSHShell.LogEvent 1, "Error: " & Title & Chr(13) & "Error Number: " & Err.Number & Chr(13) _ & "Description: " & Err.Description Err.Clear End If End Function
You can call this from a batch file (e.g. login.cmd)
@echo off set wsh=no rem Loop through folders in path and check if cscript.exe exists for %%p in (%path%) do if exist %%p\cscript.exe set wsh=yes if %wsh%==no goto wshno :wshyes cscript login.vbs goto finally :wshno echo Windows Scripting Not Installed :finally rem script has finished