Streamline Your Network Printer Management with PowerShell Scripting

Key takeaways

  • Streamlined network printer management: Automates adding or removing network printers, significantly enhancing efficiency in IT environments.
  • PowerShell capabilities: Utilizes the robustness of PowerShell for managing printers, reducing manual intervention and errors.
  • Administrative privilege requirement: Emphasizes the need for administrative rights to execute printer configuration changes.
  • Versatility in application: Suitable for diverse environments, from corporate offices to educational institutions.
  • Security awareness: Highlights the importance of script security to prevent unauthorized modifications in the printing setup.
  • Ease of use vs. manual methods: Offers a more dynamic and flexible approach compared to traditional methods like manual setup or GPOs.
  • Operational efficiency: Facilitates uniform printer configuration across multiple workstations, saving time and resources.
  • Compatibility and requirements: Supports Windows 10 and Windows Server 2016 onwards, ensuring broad applicability.
  • Automation with NinjaOne: Demonstrates how integrating such scripts with NinjaOne can further streamline IT management tasks.

Introduction

Managing network printers efficiently is a vital aspect of IT infrastructure in organizations. The automation of adding or removing printers using PowerShell scripts not only streamlines the process but also enhances productivity and minimizes human error. PowerShell, with its robust scripting capabilities, plays a pivotal role in automating routine tasks in the IT domain.

Background

The script in focus is designed to add or remove a shared printer from a network. This functionality is particularly crucial for IT professionals and Managed Service Providers (MSPs) who manage a large number of client workstations. By automating this task, IT teams can ensure that all users have consistent access to necessary printers, reducing manual setup time and improving overall workflow efficiency.

The script:

 

#Requires -Version 5.1

<#
.SYNOPSIS
    Adds a shared printer from a server on the network as an "All User Printer".
.DESCRIPTION
    Adds a shared printer from a server on the network as an "All User Printer".

.EXAMPLE
    -Server 'PrintServer.example.com' -Name 'LobbyPrinter'

    WARNING: Waiting for service 'Print Spooler (Spooler)' to start...
    Restarted print Spooler service.
    Adding printer complete.
    WARNING: A restart is required for this script to take immediate effect.

PARAMETER: -Server 'PrintServer.example.com'
    Server name that is hosting the shared printer.
    Required.
PARAMETER: -Name 'LobbyPrinter'
    Name of the printer that is being shared.
    Required.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$Server,
    [Parameter()]
    [String]$Name,
    [Parameter()]
    [Switch]$Remove = [System.Convert]::ToBoolean($env:removePrinter),
    [Parameter()]
    [Switch]$Restart = [System.Convert]::ToBoolean($env:forceRestart)
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    if ($env:server -and $env:server -notlike "null") { $Server = $env:server }
    if ($env:printerName -and $env:printerName -notlike "null") { $Name = $env:printerName }

    Write-Host ""

    if (-not $Server) {
        Write-Host "[Error] Please specify a Server."
        exit 1
    }
    if (-not $Name) {
        Write-Host "[Error] Please specify a Printer Name."
        exit 1
    }

    $ProcessTimeOut = 10
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    try {
        $StartTime = Get-Date
        $AddOrRemove = if($Remove){"/gd"}else{"/ga"}

        Add-Printer -Connection "\\$Server\$Name"

        $Printer = Get-Printer -ComputerName $Server -Name $Name
        $PrinterDriver = Get-PrinterDriver -Name $Printer.DriverName -ComputerName $Server

        # rundll32.exe printui.dll, PrintUIEntry /ga /n\\$Server\$Name
        $Process = Start-Process -FilePath "C:\WINDOWS\system32\rundll32.exe" -ArgumentList @(
                "printui.dll,", "PrintUIEntry", $AddOrRemove, "/n`"\\$Server\$Name`""
        ) -PassThru -NoNewWindow

        # Wait for process to exit
        while (-not $Process.HasExited) {
            if ($StartTime.AddMinutes($ProcessTimeOut) -lt $(Get-Date)) {
                Write-Error -Message "[Error] rundll32.exe printui.dll took longer than $ProcessTimeOut minutes to complete." -Category LimitsExceeded -Exception (New-Object System.TimeoutException)
                exit 1
                break
            }
            Start-Sleep -Milliseconds 100
        }

        Add-PrinterDriver -Name $PrinterDriver.Name

        Restart-Service -Name Spooler

        if ($(Get-Service -Name Spooler).Status -like "Running") {
            Write-Host "Restarted print Spooler service."
            Write-Host "Adding printer complete."
        }
        else {
            Write-Host "[Error] Failed to restart Spooler service."
            exit 1
        }

        if($Restart){
            Write-Warning "A restart was requested scheduling restart for 60 seconds from now."
            Start-Process shutdown.exe -ArgumentList "/r /t 60" -Wait -NoNewWindow
        }else{
            Write-Warning "A restart may be required for this script to take immediate effect."
        }
    }
    catch {
        Write-Error $_
        Write-Host "[Error] Failed to add network printer."
        exit 1
    }
    exit 0
}
end {
    
    
    
}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script operates in several steps:

  • Preparation: It checks for necessary parameters like the server hosting the printer and the printer name. It also verifies if the script is run with administrative privileges.
  • Printer addition or removal: It uses the ‘Add-Printer’ cmdlet for adding a printer or modifies the script for removal. Additionally, it employs rundll32.exe along with printui.dll to add the printer for all users on the network.
  • Driver management and service restart: The script fetches the printer driver from the server and adds it if not already present. It then restarts the ‘Print Spooler’ service, essential for activating the printer on the network.
  • Final steps and restart option: After successfully adding the printer, the script outputs the status. If a restart flag is set, it schedules a system restart to ensure changes take effect immediately.

Potential use cases

Imagine an IT administrator at a large school who needs to add a new printer to all computers in a lab. Instead of manually adding the printer to each computer, the administrator runs this script, significantly reducing setup time and ensuring all computers are uniformly configured.

Comparisons

Traditionally, network printers were added manually or via Group Policy Objects (GPOs) in Windows environments. This script offers a more direct and scriptable approach, allowing for dynamic changes and on-the-fly updates, something GPOs can’t easily offer.

FAQs

  • Q: Can this script be used on any Windows machine?
    A: It supports Windows 10 and Windows Server 2016 onwards.
  • Q: Is administrative privilege mandatory for running this script?
    A: Yes, administrative rights are required to make changes to printer settings.

Implications

While this script simplifies printer management, it also implies potential security risks if misused. Unauthorized access to the script could lead to unwanted changes in the printing environment. Proper permissions and script management are essential.

Recommendations

  • Regularly update the script to match the evolving network environment.
  • Maintain strict access controls to the script.
  • Test the script in a controlled environment before widespread deployment.

Final thoughts

In a world where IT efficiency is paramount, scripts like this exemplify how NinjaOne can be a valuable asset. With NinjaOne, IT professionals can deploy scripts across multiple devices, monitor their execution, and ensure optimal IT infrastructure performance. This script, combined with the capabilities of NinjaOne, represents a significant step towards automated and efficient IT management. 

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).