Get-AttachedPrinterStatus.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID f6aa63a7-4632-4bfc-94bb-d212ee9bacd6
 
.AUTHOR Kalichuza
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Returns the status of all or a single connected printer (whether is connected or not)
 
#>
 
# Script to check printers based on connection type using CIM

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [ValidateSet('USB', 'Network', 'WSD')]
    [string]$ConnectionType,

    [Parameter(Mandatory = $false)]
    [string]$PrinterName
)

try {
    # Determine the connection type filter
    switch ($ConnectionType) {
        'USB' {
            $printers = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.PortName -match 'USB' }
        }
        'Network' {
            $printers = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.PortName -match 'IP_' }
        }
        'WSD' {
            $printers = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.PortName -match 'WSD' }
        }
    }

    # Filter by printer name if provided
    if ($PrinterName) {
        $printers = $printers | Where-Object { $_.Name -like "*$PrinterName*" }
    }

    # Display printer status
    if ($printers) {
        $printers | ForEach-Object {
            $status = if ($_.WorkOffline -eq $false -and $_.PrinterStatus -eq 3) { "Online" } else { "Offline or Unavailable" }
            Write-Output "Printer: $($_.Name) | Status: $status | Port: $($_.PortName)"
        }
    }
    else {
        Write-Output "No printers found with the specified connection type."
    }
}
catch {
    Write-Error "An error occurred: $_"
}