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

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

    Join 1,765 other followers

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: