Public/Printing/Clear-PrintJobs.ps1

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


FUNCTION Clear-PrintJobs {
    <#
    .SYNOPSIS
    Clears all print jobs for a specified printer or all printers.
 
    .DESCRIPTION
    This function clears all print jobs for a specified printer or all printers. If print jobs are found, they are removed, and a confirmation message is displayed. If no print jobs are found, an appropriate message is displayed.
 
    .PARAMETER Name
    Specifies the name of the printer for which to clear print jobs.
 
    .PARAMETER All
    Indicates that the function should clear print jobs for all printers.
 
    .EXAMPLE
    Clear-PrintJobs -Name "Printer1"
    Clears all print jobs for the printer named "Printer1".
 
    .EXAMPLE
    Clear-PrintJobs -All
    Clears all print jobs for all printers.
 
    .INPUTS
    System.String. The function accepts a string input for the printer name.
    System.Management.Automation.SwitchParameter. The function accepts a switch parameter to clear jobs for all printers.
 
    .OUTPUTS
    None. The function does not return any output.
 
    .NOTES
    Ensure you have the necessary permissions to manage print jobs.
    #>


    [CmdletBinding(DefaultParameterSetName = 'ByName')]
    param (
        [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'ByName', ValueFromPipeline = $true)]
        [string]$Name,

        [Parameter(ParameterSetName = 'All')]
        [switch]$All
    )

    process {
        if ($PSCmdlet.ParameterSetName -eq 'All') {
            $printers = Get-Printer
            foreach ($printer in $printers) {
                $jobs = Get-PrintJob -PrinterName $printer.Name
                if ($jobs) {
                    $jobs | Remove-PrintJob
                    Write-Host "Cleared all print jobs for printer '$($printer.Name)'."
                    RETURN $null
                } else {
                    Write-Host "No print jobs to clear for printer '$($printer.Name)'."
                    RETURN $null
                }
            }
        } else {
            $jobs = Get-PrintJob -PrinterName $Name
            if ($jobs) {
                $jobs | Remove-PrintJob
                Write-Host "Cleared all print jobs for printer '$Name'."
                RETURN $null
            } else {
                Write-Host "No print jobs to clear for printer '$Name'."
                RETURN $null
            }
        }
    }
}