Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Map TCP/IP printer script verification 3

Status
Not open for further replies.

Dbyte

Technical User
Mar 6, 2002
87
0
0
My goal is to map TCP/IP printers as part of user login scripts. I've written a test script to verify it works on my own PC - it doesn't. Here's my code:
Code:
Option Explicit

Dim oWMIService, oNewPort

Set oWMIService = GetObject("winmgmts:")
Set oNewPort = oWMIService.Get _
("Win32_TCPIPPrinterPort").SpawnInstance_
oNewPort.Name = "Test_Printer"
oNewPort.Protocol = 1
oNewPort.HostAddress = "192.168.1.32"
oNewPort.PortNumber = "9100"
oNewPort.SNMPEnabled = False
oNewPort.Put_
The IP address is valid for the printer & the port is not already in use. If I go through the process manually (add local printer, etc.) w/ the values in the script above it works fine. I am not getting any errors from the script, nor can I find any typos. What am I missing??
 
Your script would add a local IP PORT not a printer.

You would also need something like this to assign a printer to the port that your script is adding.

Code:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_

objPrinter.DriverName = "HP LaserJet 4000 Series PS"
objPrinter.PortName   = "IP_169.254.110.160"
objPrinter.DeviceID   = "ScriptedPrinter"
objPrinter.Location = "USA/Redmond/Building 37/Room 114"
objPrinter.Network = True
objPrinter.Shared = True
objPrinter.ShareName = "ScriptedPrinter"
objPrinter.Put_


Is that what you mean to do? That will turn every everyones PC into print queues for the remote printer.






Here is a logon script I developed for connecting users to remote IP printers. Many of the users here will recognize their handy work in this script as they helped on it about 6 months ago.

Code:
On Error Resume Next 

Set WSHShell = CreateObject("WScript.Shell")
Set WSHNetwork = CreateObject("WScript.Network")

'Automatically find the domain name
Set objDomain = getObject("LDAP://rootDse")
DomainString = objDomain.Get("dnsHostName")
'Find the Windows Directory
WinDir = WshShell.ExpandEnvironmentStrings("%WinDir%")

'Grab the user name
UserString = WSHNetwork.UserName

'Bind to the user object to get user name and check 
'for group memberships later
Set UserObj = GetObject("WinNT://" & DomainString & "/" & UserString)

	strUser = UserObj.Name 'store users full name 
	strBank = (Left(UserObj.Name,3)) ' Grab the first 3 characters of the username
	
'	WScript.Echo UCase(strBank)
'	WScript.Echo "strUser: " & vbCrLf & strUser & vbCrLf
'	WScript.Echo "DomainString: " & vbCrLf & DomainString & vbCrLf
'	WScript.Echo "UserString: " & vbCrLf & UserString & vbCrLf

'****************************************************************************
' Remove ALL old printers
'****************************************************************************
'Set WSHPrinters = WSHNetwork.EnumPrinterConnections
'For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2

'To remove only networked printers use this If Statement

'	If Left(WSHPrinters.Item(LOOP_COUNTER +1),2) = "\\" Then
'		WSHNetwork.RemovePrinterConnection WSHPrinters.Item(LOOP_COUNTER +1),True,True
'	End If
'Next


'*****************************************************************************
'Now check for group memberships and select the correct Case
'*****************************************************************************
	strCounter = 0 ' Initialize counter
	For Each GroupObj In UserObj.Groups
		'WScript.Echo UCase(GroupObj.Name) ' (Insert echo command for troubleshooting)

    Select Case UCase(GroupObj.Name) ' Convert to Upper Case for consistency

'****************************************************************************
' Connect to printers for Harrison Bank
'****************************************************************************

		Case "052"
		
		'**************************************************************
		' Remove Old Printers
		'**************************************************************
		'Check if a specific printer exists already  Returns -1 
		'if printer exists, 0 if printer not present
		'**************************************************************

'		Set WSHPrinters = WSHNetwork.EnumPrinterConnections
'		PrinterPath = ""
'		PrinterExists = False
'		For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
'		    If WSHPrinters.Item(LOOP_COUNTER +1) = PrinterPath Then
'		       PrinterExists = True
'		    End If
'		Next
'			If PrinterExists <> 0 then
'				WSHNetwork.RemovePrinterConnection PrinterPath, True, True
'			End If 
		

		'**************************************************************
		'Check if a specific printer exists already  Returns -1 
		'if printer exists, 0 if printer not present
		'**************************************************************
		'**************************************************************
		'Connect to printers on new Print Server
		'**************************************************************

		Set WSHPrinters = WSHNetwork.EnumPrinterConnections
		PrinterPath = "\\LXOLCDPRN01\052 LP1"
		PrinterExists = False
		For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
		    If WSHPrinters.Item(LOOP_COUNTER +1) = PrinterPath Then
		       PrinterExists = True
		    End If
		Next
			If PrinterExists = 0 then
				WSHNetwork.AddWindowsPrinterConnection PrinterPath
'				WScript.Echo PrinterExists
			End If 
			
		Set WSHPrinters = WSHNetwork.EnumPrinterConnections
		PrinterPath = "\\LXOLCDPRN01\052 LP2"
		PrinterExists = False
		For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
		    If WSHPrinters.Item(LOOP_COUNTER +1) = PrinterPath Then
		       PrinterExists = True
		    End If
		Next
			If PrinterExists = 0 then
				WSHNetwork.AddWindowsPrinterConnection PrinterPath
'				WScript.Echo PrinterExists
			End If 
			
		Set WSHPrinters = WSHNetwork.EnumPrinterConnections
		PrinterPath = "\\LXOLCDPRN01\052 PECULIAR"
		PrinterExists = False
		For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
		    If WSHPrinters.Item(LOOP_COUNTER +1) = PrinterPath Then
		       PrinterExists = True
		    End If
		Next
			If PrinterExists = 0 then
				WSHNetwork.AddWindowsPrinterConnection PrinterPath
'				WScript.Echo PrinterExists
			End If 
			
		Set WSHPrinters = WSHNetwork.EnumPrinterConnections
		PrinterPath = "\\LXOLCDPRN01\052 PLOBBY"
		PrinterExists = False
		For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
		    If WSHPrinters.Item(LOOP_COUNTER +1) = PrinterPath Then
		       PrinterExists = True
		    End If
		Next
			If PrinterExists = 0 then
				WSHNetwork.AddWindowsPrinterConnection PrinterPath
'				WScript.Echo PrinterExists
			End If 
			
		Set WSHPrinters = WSHNetwork.EnumPrinterConnections
		PrinterPath = "\\LXOLCDPRN01\052 TELLER"
		PrinterExists = False
		For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
		    If WSHPrinters.Item(LOOP_COUNTER +1) = PrinterPath Then
		       PrinterExists = True
		    End If
		Next
			If PrinterExists = 0 then
				WSHNetwork.AddWindowsPrinterConnection PrinterPath
'				WScript.Echo PrinterExists
			End If 
			
		

'****************************************************************************
' Set default and other printer setting bases on security groups
'****************************************************************************
'****************************************************************************
' Raymore
'****************************************************************************

        Case "052 LP1"
            'Below is an example of how to set the default printer
            WSHNetwork.SetDefaultPrinter "\\LXOLCDPRN01\052 LP1"
        Case "052 LP2"
            'Below is an example of how to set the default printer
            WSHNetwork.SetDefaultPrinter "\\LXOLCDPRN01\052 LP2"
        Case "052 PECULIAR"
            'Below is an example of how to set the default printer
            WSHNetwork.SetDefaultPrinter "\\LXOLCDPRN01\052 PECULIAR"
        Case "052 PLOBBY"
            'Below is an example of how to set the default printer
            WSHNetwork.SetDefaultPrinter "\\LXOLCDPRN01\052 PLOBBY"
        Case "052 TELLER"
            'Below is an example of how to set the default printer
            WSHNetwork.SetDefaultPrinter "\\LXOLCDPRN01\052 TELLER"
	End Select
	Next

Hope this helps you.



Thanks

John Fuhrman
Titan Global Services
 
Sparkbyte, My goal is to map printers as TCP/IP ports to allow PCs to communicate directly w/ printers, instead of relying on centralized print servers to manage all print jobs. This will allow us to decrease network traffic. I got the original script from here (the bottom script).

Your script above relies on print servers & name-based mapping, so that won't work for me.
 
You would have to combine your script with the first example script I left.

Here is an example that should work. The only problem with doing this as part of a logon process is that you will need a way to check to see if the printer already exists and also prepare your users for a 10 to 15 second delay per printer during their initial logon.

Code:
strIP = "192.168.1.100"
strPort = "9100"
strPrinterName = "2nd Floor HP Printer"
strLocation = "2nd Floor"
strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNewPort = objWMIService.Get _
    ("Win32_TCPIPPrinterPort").SpawnInstance_

objNewPort.Name = "IP_" & strIP
objNewPort.Protocol = 1
objNewPort.HostAddress = strIP
objNewPort.PortNumber = strPort
objNewPort.SNMPEnabled = False
objNewPort.Put_


'strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_

objPrinter.DriverName = "HP LaserJet 4000 Series PS"
objPrinter.PortName   = "IP_" & strIP
objPrinter.DeviceID   = strPrinterName
objPrinter.Location = strLocation
objPrinter.Network =  False 'True
objPrinter.Shared = False ' True
'objPrinter.ShareName = "ScriptedPrinter"
objPrinter.Put_


Thanks

John Fuhrman
Titan Global Services
 
Hi sparkbyte,

Just a thought to reduce the number of times you enumerate through the printers...

Code:
' create a dictionary to store our printer paths
Set objDictPrnts = CreateObject("Scripting.Dictionary")
objDictPrnts.CompareMode = vbTextCompare
objDictPrnts.Add "\\LXOLCDPRN01\052 LP1", "\\LXOLCDPRN01\052 LP1"
objDictPrnts.Add "\\LXOLCDPRN01\052 LP2", "\\LXOLCDPRN01\052 LP2"
objDictPrnts.Add "\\LXOLCDPRN01\052 PECULIAR", "\\LXOLCDPRN01\052 PECULIAR"
objDictPrnts.Add "\\LXOLCDPRN01\052 PLOBBY", "\\LXOLCDPRN01\052 PLOBBY"
objDictPrnts.Add "\\LXOLCDPRN01\052 TELLER", "\\LXOLCDPRN01\052 TELLER"

' loop through printer connections
Set WSHPrinters = WSHNetwork.EnumPrinterConnections
For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
	PrinterPath = WSHPrinters.Item(LOOP_COUNTER +1)
	' if the current path exist in our dictionary remove it
	If objDictPrnts.Exists(PrinterPath) Then objDictPrnts.Remove PrinterPath
Next

' loop through the path's that were not found and add them
For Each PrinterPath In objDictPrnts.Keys
	WSHNetwork.AddWindowsPrinterConnection PrinterPath
Next

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Very nice idea dm4ever. Any objections to my adding that to my login script FAQ? Is it your idea or someone elses? I would want to give appropriate credit. Thanks. A star from me too.

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Thanks mark, I don't mind if you add it to your FAQ and it was my idea after seeing sparkbyte's code and thinking of a way to reduce the number of loops.

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Thanks DM4Ever. The FAQ has been updated. faq329-5798

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Just a thought, The reason I had needed the script for connecting to and setting default printers was to provide my support folks with a simple way to adjust users default printers.

This is what is in place currently.

Any other ideas and comments are welcome!!.

--------------------------------------------------------------

This script is used to great AD Global Security groups based on printer Names. (Local IP Printers on each TS application Server)
Code:
On Error Resume Next

' Get Command-line input to get the bank #'
	set args = Wscript.Arguments
		strFile = args.Item(0)

If strFile = "" Then cmdLineArgError

Const ForReading = 1
Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000

Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
'WScript.Echo "RootDSE: " & objRootDSE
'WScript.Echo "Domain: " & strDNSDomain

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(strFile, ForReading)

Do While objTextFile.AtEndOfStream <> True
  strLine = objtextFile.ReadLine
  If inStr(strLine, ",") Then
    arrDHCPRecord = split(strLine, ",")
    i = i + 1
  End If
[!] strBank = (Left(arrDHCPRecord(1),3)) 
' WScript.Echo "LDAP://ou=" & strBank & "," & strDNSDomain
[/!] 
Set objOU = GetObject("LDAP://ou=" & strBank & "," & strDNSDomain)
Set objGroup = objOU.Create("Group", "cn=" & arrDHCPRecord(1))
objGroup.Put "sAMAccountName", arrDHCPRecord(1)
objGroup.Put "groupType", ADS_GROUP_TYPE_GLOBAL_GROUP Or _
    ADS_GROUP_TYPE_SECURITY_ENABLED
objGroup.SetInfo

Loop

Sub cmdLineArgError()
	MsgBox"Please drop the Banks csv file" & vbCrLf &_
			"on this script to create the needed" & vbCrLf &_
			"security groups to set default printers.",0
	If Error = "1" Then MsgBox("Canceled")
End Sub

The Part in red will need to be adapted to needs. We prefix printer Names with Branch numbers so this works like this.

Printer Name = "100 Hp Printer Someware"

In AD, Branch 100 has an OU with it's user objects and groups.

PrinterPorts.cvs looks like this.
Code:
10.191.125.23,100 BR51_Manager,HP LaserJet 5Si

And here's the script I use to make the PrinterPorts.csv file.
Code:
strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")

For Each objPrinter in colInstalledPrinters
	If objPrinter.local = -1 Then
		If objPrinter.PortName > "TS" Then	
			Else	
	    	Add2Log		 	Mid(objPrinter.PortName,4,15) & "," &_
	    					objPrinter.DeviceID & "," &_
	     					objPrinter.DriverName
	    End If 
	End If 
Next

'objRecordSet.MoveNext
'Loop

Sub Add2Log (txt) ' txt is the text we deliver into the sub  
' Declare the log file name  
Const Myfile = ".\PrinterPorts.csv" ' Log file name  
' Open it for Append  
Const ForAppending = 8 ' Append mode  
' Declare the FileSystemObject and File variables 
  
' Create a new FileSystemObject object  
Set fso = CreateObject("Scripting.FileSystemObject")
' Open the file and force creation, if it doesn't exist already  
Set file = fso.OpenTextFile(MyFile, ForAppending, TRUE)
file.WriteLine (txt) ' append log  
' Clean up  
Set file = Nothing 
End Sub

Then this section of code is used to set the default printer and allow for an external script if the client has special needs.

Code:
For Each GroupObj In UserObj.Groups
'	WScript.Echo UCase(GroupObj.Name) ' (Insert echo command for troubleshooting)
	sExePath = "cscript //nologo "  
	sSwitches0 = "\\corebanks\SYSVOL\corebanks.jackhenry.com\scripts\"
	sFile1 = GroupObj.Name & " Printers.vbs"
		If fso.FileExists(sSwitches0 & sFile1) = True Then 
'			WScript.Echo "Found it."
			WshShell.Run sExePath & Chr(34) & sSwitches0 & sFile1 & Chr(34), 2, True 
			Exit For 
		Else
'			WScript.Echo "Setting Local Default Printer." 
			WSHNetwork.SetDefaultPrinter GroupObj.Name
		End If 	
Next


Just seemed like this solution may come in handy for Dbyte.

Oh, and the earlier posted printer script, which db4ever so graciously IMPROVED, was when we were attempting to deploy a print server which causes the need for the ability to run an external script.

Hope someone finds this useful.

Thanks

John Fuhrman
Titan Global Services
 
sparkbyte,

At my new job they still have to support old NT4 servers...apparently if it is not broken...don't fix it is the mentality. Your posts have given me an idea of quick patch for the inevitable moment when the server goes down. Have a star on me for your contributions. [thumbsup]

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Thanks very much for the star, means a lot coming from someone that has helped me so much.

The script rewrite above made me go back and do some reading on the dictionary object. That is a very slick use for it. In fact a much better example of how to use one than anything in the three books I had handy.

Thanks again for your rewrite of the printer script.

Was wondering if there would be a better way of setting the default printer based on group memberships than just rolling through the groups with a For Each / Next loop?

Thanks

John Fuhrman
Titan Global Services
 
Just one more post.

I added the ability to dynamicaly add to the dictionary by first enumerating the printers on the remote print server.

Now all I have to do is act on the branch ID and only connect to that branches printers. (I already have that bit of script worked out in another script.)

Code:
[red]
Set objDictPrnts = CreateObject("Scripting.Dictionary")
objDictPrnts.CompareMode = vbTextCompare


strComputer = "lxolcdprn01"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")

For Each objPrinter in colInstalledPrinters
' create a dictionary to store our printer paths
objDictPrnts.Add "\\" & strComputer & "\" & objPrinter.Name, _
 "\\" & strComputer & "\" & objPrinter.Name
Next
[/red]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
' loop through printer connections
Set WSHPrinters = WSHNetwork.EnumPrinterConnections
For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
    PrinterPath = WSHPrinters.Item(LOOP_COUNTER +1)
    ' if the current path exist in our dictionary remove it
    If objDictPrnts.Exists(PrinterPath) Then objDictPrnts.Remove PrinterPath
Next

' loop through the path's that were not found and add them
For Each PrinterPath In objDictPrnts.Keys
    WSHNetwork.AddWindowsPrinterConnection PrinterPath
Next

[afro2] [2thumbsup]

Thanks

John Fuhrman
Titan Global Services
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top