The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

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:

–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

 

Discover more from The Wiert Corner - irregular stream of stuff

Subscribe now to keep reading and get access to the full archive.

Continue reading