VBScript tips and tricks
Posted by jpluimers on 2013/01/22
I normally don’t do much VBScript stuff, but sometimes I have to, and these tips helped me big time:
- You can use Visual Studio 2005, 2008 SP1 or 2010 to edit VBS files (with syntax highlighting, etc)
- Debugging VBS files with cscript.exe and Visual Studio requires an extra step: you need to initiate this from the script side
–jeroen
This was the script in question (mimicked a bit after Prnmngr.vbs):
It uses AddPrinterConnection and RemovePrinterConnection of the Windows Scripting Host Network object to add/remove local LPT ports to network printers so that DOS applications can still print.
So it is equivalent to NET USE LPT1 \\servername\printershare
[sourcecode language=”vb”]
Option Explicit
On Error Resume Next
Dim objWshNetwork
Set objWshNetwork = WScript.CreateObject("WScript.Network")
‘ This is the same as "NET USE LPT#: \\servername\printername" but with extra error checking
Sub ShowError (txtMessage, txtCaption)
Call MsgBox (txtMessage, vbCritical, txtCaption)
End Sub
Sub MapPrinter(txtPort, txtNetworkPrinter, txtAlternatePort)
On Error Resume Next
Call MsgBox ("mapping " & txtPort & " to " & txtNetworkPrinter, 16, txtNetworkPrinter)
objWshNetwork.removePrinterConnection txtPort, True
‘ If Err.Number <> 0 Then
‘ Call ShowError ("Unmapping " & txtPort & "; Error # " & CStr(Err.Number) & " " & Err.Description, txtNetworkPrinter)
‘ Err.Clear
‘ End If
objWshNetwork.addPrinterConnection txtPort, txtNetworkPrinter
If Err.Number <> 0 Then
Call ShowError ("Redirecting " & txtPort & " to network printer " & txtNetworkPrinter & " failed," & _
"Error # " & CStr(Err.Number) & ": " & Err.Description _
, txtNetworkPrinter)
Err.Clear
End If
End Sub
Dim objPrinter
For Each objPrinter In GetObject("winmgmts:").ExecQuery("select * from Win32_Printer where default=true")
Dim txtNetworkPrinter
txtNetworkPrinter = objPrinter.ServerName & "\" & objPrinter.ShareName
If txtNetworkPrinter = "\" Then
Call ShowError ("You do not have a default printer that is a network printer, so there is nothing to redirect" _
, txtNetworkPrinter)
Else
Call MapPrinter("LPT1:", txtNetworkPrinter)
Call MapPrinter("LPT2:", txtNetworkPrinter)
End If
Next
[/sourcecode]






Leave a Comment