Public/Printing/Reset-Printer.ps1

<#
Copyright © 2024 Integris. For internal company use only. All rights reserved.
#>


FUNCTION Reset-Printer {
    <#
    .SYNOPSIS
    Reinstalls a specified printer by removing and re-adding it, and sets it as the default printer if it was previously the default.
 
    .DESCRIPTION
    This function reinstalls a specified printer by removing and re-adding it with the same driver and port. It also checks if the printer was the default printer and sets it as the default again if necessary. The function displays messages indicating each step of the process.
 
    .PARAMETER PrinterName
    Specifies the name of the printer to be reinstalled.
 
    .EXAMPLE
    Reset-Printer -PrinterName "Printer1"
    Reinstalls the printer named "Printer1" by removing and re-adding it, and sets it as the default printer if it was previously the default.
 
    .INPUTS
    System.String. The function accepts a string input for the printer name.
 
    .OUTPUTS
    None. The function does not return any output.
 
    .NOTES
    Ensure you have the necessary permissions to manage printers and their settings.
    #>


    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
        [string]$PrinterName
    )

    process {
        Write-Host "Reinstalling printer '$PrinterName'..."

        # Get printer information
        $printer = Get-Printer -Name $PrinterName
        if (-not $printer) {
            Write-Host "Printer '$PrinterName' not found."
            RETURN $null
        }

        # Get printer driver information
        $driver = Get-PrinterDriverInfo -PrinterName $PrinterName
        if (-not $driver) {
            Write-Host "Failed to get driver information for printer '$PrinterName'."
            RETURN $null
        }

        # Check if the printer is the default printer
        $isDefault = Test-IsDefaultPrinter -PrinterName $PrinterName

        # Get printer port information
        $port = Get-PrinterPort -Name $printer.PortName

        # Remove the printer
        Remove-Printer -Name $PrinterName
        Write-Host "Printer '$PrinterName' removed."

        # Recreate the printer
        Add-Printer -Name $PrinterName -DriverName $driver.Name -PortName $port.Name
        Write-Host "Printer '$PrinterName' reinstalled with driver '$($driver.Name)'."

        # Set the printer as default if it was the default printer
        if ($isDefault) {
            Set-DefaultPrinter -Name $PrinterName
            Write-Host "Printer '$PrinterName' set as default."
        }

        RETURN $null
    }
}
New-Alias -Name Reinstall-Printer -Value Reset-Printer