mbt masai
 
Welcome !
         

                                
After experiencing a lot of down time, We decided to move this site to CrystalTech.com. CrystalTech.com is powered by only the finest Windows servers providing the best performance, reliability, and value anywhere.

 List printers installed on a remote machine

Author Message
ginolard

  • Total Posts : 1347
  • Scores: 23
  • Reward points : 0
  • Joined: 8/11/2005
  • Status: offline
List printers installed on a remote machine Tuesday, April 24, 2007 9:12 PM (permalink)
0
I thought I had posted this on here somewhere but I guess it was only posted as part of the original ManagePC.  Oh well, here's the code that will do it.

 Const HKEY_USERS = &H80000003
 Const ForAppending = 8 
 Const OverwriteExisting = True 
 
 strComputer="REMOTE MACHINE NAME HERE" 
 Set objWbem = GetObject("winmgmts:") 
 Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv") 
 Set objWMIService = GetObject("winmgmts:"  & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
 'Go and get the currently logged on user by checking the owner of the Explorer.exe process.  
 Set colProc = objWmiService.ExecQuery("Select Name from Win32_Process" & " Where Name='explorer.exe' and SessionID=0") 
 If colProc.Count > 0 Then 
 For Each oProcess In colProc 
    oProcess.GetOwner sUser, sDomain 
 Next 
 End If 
 'Loop through the HKEY_USERS hive until (ignoring the .DEFAULT and _CLASSES trees) until we find the tree that 
 'corresponds to the currently logged on user. 
 lngRtn = objRegistry.EnumKey(HKEY_USERS, "", arrRegKeys)    
 
 For Each strKey In arrRegKeys 
 If UCase(strKey) = ".DEFAULT" Or UCase(Right(strKey, 8)) = "_CLASSES" Then 
 Else 
    Set objSID = objWbem.Get("Win32_SID.SID='" & strKey & "'") 
    
 'If the account name of the current sid we're checking matches the accountname we're looking for Then 
 'enumerate the Network subtree 
    If objSID.accountname = sUser Then 
        regpath2enumerate = strkey & "\Printers\Settings" 'strkey is the SID 
        objRegistry.enumkey HKEY_USERS, regpath2enumerate, arrkeynames 
            
 'If the array has elements, go and get the drives info from the registry 
  intCount = 0
        If Not (IsNull(arrkeynames)) Then 
            For Each subkey In arrkeynames 
                regpath = strkey & "\Printers\Settings" & subkey 
                regentry = "RemotePath" 
                objRegistry.getstringvalue hkey_users, regpath, regentry, dapath 
                intCount = intCount + 1 'increment
                arrRead = sUser &  vbTab & subkey & ":" & vbTab & dapath & vbTab & vbLf 
                strArray = strArray & arrRead
            Next 
             WScript.Echo strArray
        Else
            WScript.Echo "No printers defined"
        End If 
    End If 
 End If 
 Next 
 
 
Author of ManagePC - http://managepc.net

#1
    TomRiddle

    • Total Posts : 608
    • Scores: 12
    • Reward points : 0
    • Joined: 2/7/2008
    • Location: Australia
    • Status: offline
    Re:List printers installed on a remote machine Wednesday, March 03, 2010 4:25 PM (permalink)
    4
    I stumbled upon this today looking for a script that reads remote network printers used in the profile of a user. While this script looked promising it only enumerates registry keys not values, the printers are stored in the registry as values, Sheepz had the same problem and I don't think he got it working. http://www.visualbasicscript.com/tm.aspx?m=46265
     
    I thought I would share an alternate version I just wrote that works for me.
     
     
     
    'Script By Tommriddle 2010 - List All Network printers installed in the profile of a user on a remote machine.
    forceUseCScript
    Sub forceUseCScript()
      
    Set oShell = CreateObject("Wscript.Shell")
       If Not WScript.FullName = WScript.Path & "\cscript.exe" Then
          oShell.Run "cmd.exe /k " & WScript.Path & "\cscript.exe //NOLOGO " & Chr(34) & WScript.scriptFullName & Chr(34),1,False
          WScript.Quit 0
       End If
    End Sub
    strComputer=inputbox("Enter PC Name")
    CU=GetCurrentUser(strComputer)
    CUSID = GetSIDFromUser(CU)
    strKeyPath = CUSID & "\Printers\settings"
     
    'Enumerate Registry Values
    'http://www.activexperts.c...istry/#EnumRegVals.htm
    Const HKEY_USERS = &H80000003
    const REG_SZ = 1
    const REG_EXPAND_SZ = 2
    const REG_BINARY = 3
    const REG_DWORD = 4
    const REG_MULTI_SZ = 7
     
    Set StdOut = WScript.StdOut
     
    Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
    strComputer & "\root\default:StdRegProv")
     
    oReg.EnumValues HKEY_USERS, strKeyPath, arrValueNames, arrValueTypes
     
    For i=0 To UBound(arrValueNames)
        StdOut.WriteLine "Printer: " & arrValueNames(i)
        StdOut.Writeline "User: " & CU
        StdOut.WriteBlankLines(1)
    Next
     
    '-----------------------------------------------------------------------
     
    Function GetCurrentUser(strComputer)
    'Input: strComputer = machine to query
    'Output: Current User as domain\logon
    'Only works on XP/W2003
       on error resume next
       Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
       Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'explorer.exe'")
       For Each objProcess in colProcessList
          objProcess.GetOwner strUserName, strUserDomain
       Next
       GetCurrentUser = strUserDomain & "\" & strUserName
       if err<> 0 then
          Msgbox " Error accessing remote machine"
          wscript.quit
       end if
       on error goto 0
    End Function
     
    '-----------------------------------------------------------------------
     
    Function GetSIDFromUser(UserName)
    'Input: UserName as domain\logon
    'Output: SID
    'http://groups.google.com/...t/msg/1bd0d208ef41dda7
       Dim DomainName, Result, WMIUser
       If InStr(UserName, "\") > 0 Then
          DomainName = Mid(UserName, 1, InStr(UserName, "\") - 1)
          UserName = Mid(UserName, InStr(UserName, "\") + 1)
       Else
          DomainName = CreateObject("WScript.Network").UserDomain
       End If
       On Error Resume Next
       Set WMIUser = GetObject("winmgmts:{impersonationlevel=impersonate}!" _
          & "/root/cimv2:Win32_UserAccount.Domain='" & DomainName & "'" _
             & ",Name='" & UserName & "'")
       If Err = 0 Then Result = WMIUser.SID Else Result = ""
       On Error GoTo 0
       GetSIDFromUser = Result
    End Function
     
    '-----------------------------------------------------------------------
     
     
    -join([int[]][char[]]'Ut|jwXmjqq%Wzqjx'|%{[char]($_-5)})
    #2
      Deckyon

      • Total Posts : 45
      • Scores: 0
      • Reward points : 0
      • Joined: 8/1/2006
      • Location: Louisville, KY - USA
      • Status: offline
      Re:List printers installed on a remote machine Thursday, March 04, 2010 1:20 AM (permalink)
      0
      Here is a WMI version I wrote the other week.  it lists printers attached to the computer.  It is possible to run based on either Name or IP.  Also, it saves the information in a text file.

      '==========================================================================' 
       ' Title:   List Printers.vbs' 
       ' Date:    02/23/2010' 
       ' Author:  Bradley Buskey' 
       ' Version: 1.00' 
       ' Updated: 02/23/2010' 
       ' Purpose: List all printers attached to a workstation' 
       '==========================================================================' 
       Const ForAppending = 8 
       Const ForReading = 1 
       
       strComputer = inputbox("Please enter the computer name or IP address.","Computer Name",".") 
       
       Set WshNetwork = CreateObject("WScript.Network") 
       Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
       Set colInstalledPrinters =  objWMIService.ExecQuery("Select * from Win32_Printer") 
       Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48) 
       Set WshShell = WScript.CreateObject("WScript.Shell") 
       Set objFSO = CreateObject("Scripting.FileSystemObject") 
       
       For Each objItem in colItems 
           UserName = objItem.UserName 
           arrUserName = Split(UserName, "\", -1, 1) 
           varUserName = arrUserName(1) 
       Next 
       
       filOutput = varUserName & ".txt" 
       
       If objFSO.FileExists(filOutput) Then 
           objFSO.DeleteFile(filOutput) 
       End If 
       
       Set objOutputFile = objFSO.OpenTextFile (filOutput, ForAppending, True) 
       For Each objPrinter in colInstalledPrinters 
           strTest = Left(objPrinter.Name, 2) 
           objOutputFile.WriteLine(objPrinter.Name) 
       Next 
       
       objOutputFile.Close 
       
       varOpen = MsgBox("Do you want to view the printers?",36,"View File?") 
       If varOpen = vbYes Then 
           varCommand = "notepad " & filOutput 
           WshShell.Run varCommand,1,False 
       End If 
       
       Wscript.Sleep 1500 
       MsgBox "Printer mappings have been stored in '" & filOutput & "'.", 64, "Script Complete" 
       Wscript.Quit

      #3
        TomRiddle

        • Total Posts : 608
        • Scores: 12
        • Reward points : 0
        • Joined: 2/7/2008
        • Location: Australia
        • Status: offline
        Re:List printers installed on a remote machine Sunday, March 07, 2010 3:06 PM (permalink)
        0
        Thanks Deckyon,
         
        Thanks, I added yours to mine and now I can get the printers installed locally on the remote machine also.
        I think you need a combination of both for some network environments.
         
        Deckyon


        Here is a WMI version I wrote the other week.  it lists printers attached to the computer.  It is possible to run based on either Name or IP.  Also, it saves the information in a text file.

        '==========================================================================' 
             ' Title:   List Printers.vbs' 
             ' Date:    02/23/2010' 
             ' Author:  Bradley Buskey' 
             ' Version: 1.00' 
             ' Updated: 02/23/2010' 
             ' Purpose: List all printers attached to a workstation' 
             '==========================================================================' 
             Const ForAppending = 8 
             Const ForReading = 1 
             
             strComputer = inputbox("Please enter the computer name or IP address.","Computer Name",".") 
             
             Set WshNetwork = CreateObject("WScript.Network") 
             Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
             Set colInstalledPrinters =  objWMIService.ExecQuery("Select * from Win32_Printer") 
             Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48) 
             Set WshShell = WScript.CreateObject("WScript.Shell") 
             Set objFSO = CreateObject("Scripting.FileSystemObject") 
             
             For Each objItem in colItems 
                UserName = objItem.UserName 
                arrUserName = Split(UserName, "\", -1, 1) 
                varUserName = arrUserName(1) 
             Next 
             
             filOutput = varUserName & ".txt" 
             
             If objFSO.FileExists(filOutput) Then 
                objFSO.DeleteFile(filOutput) 
             End If 
             
             Set objOutputFile = objFSO.OpenTextFile (filOutput, ForAppending, True) 
             For Each objPrinter in colInstalledPrinters 
                strTest = Left(objPrinter.Name, 2) 
                objOutputFile.WriteLine(objPrinter.Name) 
             Next 
             
             objOutputFile.Close 
             
             varOpen = MsgBox("Do you want to view the printers?",36,"View File?") 
             If varOpen = vbYes Then 
                varCommand = "notepad " & filOutput 
                WshShell.Run varCommand,1,False 
             End If 
             
             Wscript.Sleep 1500 
             MsgBox "Printer mappings have been stored in '" & filOutput & "'.", 64, "Script Complete" 
             Wscript.Quit



        -join([int[]][char[]]'Ut|jwXmjqq%Wzqjx'|%{[char]($_-5)})
        #4
          windowlicker

          • Total Posts : 1
          • Scores: 0
          • Reward points : 0
          • Joined: 3/10/2011
          • Status: offline
          Re:List printers installed on a remote machine Thursday, March 10, 2011 10:57 AM (permalink)
          0
          Tomm

          I get an error when running this against a windows 7 machine.  as I am a noob when it comes to VB is there a way to change it to a wildcard, or any?  below is what I receive when I run it.

          C:\Users\%username%\Desktop\Network Printers.vbs(32, 1) Microsoft VBScript runtime error: Type mismatch: 'UBound'

          Any suggestions?

          TomRiddle



          For i=0 To UBound(arrValueNames)
          StdOut.WriteLine "Printer: " & arrValueNames(i)
          StdOut.Writeline "User: " & CU
          StdOut.WriteBlankLines(1)




          #5
            tnory

            • Total Posts : 1
            • Scores: 0
            • Reward points : 0
            • Joined: 6/27/2011
            • Status: offline
            Re:List printers installed on a remote machine Monday, June 27, 2011 6:32 AM (permalink)
            0
            I did this for our implementation, we needed to change a print server to another server so every time a user logs in we will run this code to replace the names of the printers. I tested it on win 7 boxes and XP pro machines. Let me know if it is of any help.
             
            Thanks!
             
             '==========================================================================' 
             ' Title:    get_printers.vbs'
             ' Date:        06/20/2011' 
             ' Author:    Thomas Norberg' 
             ' Version:    1.02' 
             ' Updated:    06/24/2011' 
             ' Purpose:    List all Networked printers attached to a workstation delete and create new printer mapping' 
             ' Usage:    Replace all printers with a new server'
             ' Set "printerServerName" to be the current server you want to replace'
             ' Set "printerReplaceWith" to be the new server that is taking the old server name'
             ' Set "groupAdd" to false to disable group adding feature'
             ' e.g.: \\printerServerName\NameofPrinter Replace With \\printerReplaceWith\NameofPrinter'
             ' Explanation:    When you add or delete a printer for the group (e.g.  anyone that logs into the computer) it will be added or deleted for  everyone.'
             ' For instance: if you just use "objPrinter.Delete_" call and the  printer is added to the group it will not get deleted permanently but,'
             ' NOTE: If you use the "Group Delete Printer" line it will throw an error if the printer is not a group added printer.'
             ' NOTE: If you use the "Group Add Printer" line and it is already a group added printer is will also throw and error.'
             ' Generally it is safe to assume that we can try to "Group Delete  Printer" everytime to reduce errors but if initially the printer is not  grouped it will throw and error.'
             ' !!!!! NOTE: Might need to restart print spooler to make changes on the fly like this script will perform. !!!!!'
             '==========================================================================' 
             
             Wscript.Sleep 20000 ' This is to wait 20seconds after the computer starts before trying to add or delete printers'
             On Error Resume Next ' !!!! IMPORTANT: because we need to make sure the  script continues if errors occur: e.g. not finding all printers with  "printerServerName" in them !!!'
             ' Change this to search for different server name'
             printerServerName = "oldServerName" 'Need to change this
             ' Change this to replace the "printerServerName"'
             printerReplaceWith = "newServerName" 'Need to change this
             ' Set to true to group add printers'
             groupAdd = true
             
             Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") 
             Set colInstalledPrinters = objWMIService.ExecQuery("Select * from  Win32_Printer Where (Name Like '%" & printerServerName & "%')  AND Network = true") 
             Set WshShell = WScript.CreateObject("WScript.Shell") 
             Set objNetwork = CreateObject("WScript.Network")
             
             '============= Remove old printer and add newly networked printer ==========='
             For Each objPrinter in colInstalledPrinters 
             splitPrinter = Split(objPrinter.Name, "\", -1, 1)
             printerPath = "\\" & LCase(splitPrinter(2)) & "\" & splitPrinter(3)
             ' Wscript.Echo "Default: " & objPrinter.Default'
             If objPrinter.Default = true Then
             defaultPrinter = splitPrinter(3)
             End If
             ' Call Command to group delete the printer from the computer and delete from devices'
             WshShell.run "rundll32 printui.dll,PrintUIEntry /gd /n" & Chr(34)  & LCase(objPrinter.Name) & Chr(34) &"" ' Group Delete  Printer'
             objPrinter.Delete_ 'Delete the printer mapping, if not grouped delete anyway to remove the older name'
             printerPath = Replace(printerPath, LCase(printerServerName), printerReplaceWith) ' Set and rename the printer mapping'
             ' Call Command to group add the printer to the computer and add printer to the devices'
             If groupAdd = true then
             WshShell.run "rundll32 printui.dll,PrintUIEntry /ga /n" & Chr(34)  & printerPath & Chr(34) &"" ' Group Add Printer'
             End If
             objNetwork.AddWindowsPrinterConnection printerPath 
             Next
             
             '============= Set the default printer based on the previously selected default printer ==========='
             Wscript.Sleep 10000
             Set colInstalledPrinters =  objWMIService.ExecQuery ("Select * from  Win32_Printer Where Name = '" & defaultPrinter & "'")
             For Each objPrinter in colInstalledPrinters
             objPrinter.SetDefaultPrinter()
             Next 

            #6

              Online Bookmarks Sharing: Share/Bookmark

              Jump to:

              Current active users

              There are 0 members and 1 guests.

              Icon Legend and Permission

              • New Messages
              • No New Messages
              • Hot Topic w/ New Messages
              • Hot Topic w/o New Messages
              • Locked w/ New Messages
              • Locked w/o New Messages
              • Read Message
              • Post New Thread
              • Reply to message
              • Post New Poll
              • Submit Vote
              • Post reward post
              • Delete my own posts
              • Delete my own threads
              • Rate post

              2000-2012 ASPPlayground.NET Forum Version 3.8
              mbt shoes www.wileywilson.com