Get default printer remotely

前端 未结 2 937
太阳男子
太阳男子 2021-01-21 05:12

Windows 7:

cscript C:\\Windows\\System32\\Printing_Admin_Scripts\\en-US\\prnmngr.vbs -g

Windows XP:

cscript C:\\windows\\syste         


        
2条回答
  •  一生所求
    2021-01-21 06:09

    This script will return the specified computer's currently-logged-in user's default printer (read from the Registry).

    We're trying to clean up some network printer connections, and a script like this that shows the shared printers that a user is connected to is something we really need.

    My primary challenge was figuring out a way to get at the "current user" information (as opposed to the "computer" information). The shared printer connections are stored in the user area, so that's where I needed to be.

    I pieced together information from several sources to do it this way:

    • Determine the logged-in user (account)
    • Get the SID for that user
    • Use the SID to navigate to the user's HKEY_USERS Registry hive
    • Output the value in SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\Device. Before coding I determined that this Registry value is updated immediately upon a default printer change. BONUS: You can also change/set the user's default printer by updating this Registry value.
    # ---------------------------------------------------------------------------
    #
    # This script requires a computer name.  It will return the computer's 
    # currently logged-in user's default printer.
    #
    # ---------------------------------------------------------------------------
    
    # Set the variable below to choose your computer
    $Computer = "computer_name"
    
    
    # get the logged-in user of the specified computer
    $user = Get-WmiObject –ComputerName $computer –Class Win32_ComputerSystem | Select-Object UserName
    
    # get that user's AD object
    $AdObj = New-Object System.Security.Principal.NTAccount($user.UserName)
    
    # get the SID for the user's AD Object 
    $strSID = $AdObj.Translate([System.Security.Principal.SecurityIdentifier])
    
    # get a handle to the "USERS" hive on the computer
    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("Users", $Computer)
    
    # get a handle to the current user's USERS Registry key where the default printer value lives
    $regKey = $reg.OpenSubKey("$strSID\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows")
    
    # read and show the new value from the Registry for verification
    $regValue = $regKey.GetValue("Device")
    write-output $regValue
    write-output " "
    write-output " "
    [void](Read-Host 'Press Enter to continue…')
    

提交回复
热议问题