71 lines
2.5 KiB
PowerShell
71 lines
2.5 KiB
PowerShell
param(
|
|
[string[]]$PrinterNames, # Printers to monitor, empty array means all
|
|
[int]$IntervalSeconds = 2 # Polling interval (seconds)
|
|
)
|
|
$OutputEncoding = [System.Text.Encoding]::UTF8
|
|
if (-not $PrinterNames) { $PrinterNames = @() }
|
|
|
|
Write-Host "========================================" -ForegroundColor Cyan
|
|
Write-Host " Printer Status Monitor" -ForegroundColor Cyan
|
|
Write-Host "========================================" -ForegroundColor Cyan
|
|
Write-Host "Start time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
|
|
if ($PrinterNames.Count -gt 0) {
|
|
Write-Host "Monitoring printers: $($PrinterNames -join ', ')"
|
|
} else {
|
|
Write-Host "Monitoring all printers"
|
|
}
|
|
Write-Host "Press Ctrl+C to stop monitoring"
|
|
Write-Host ""
|
|
|
|
# Cache last status to avoid duplicate output
|
|
$lastStatus = @{}
|
|
|
|
function Get-PrinterStatusText($status) {
|
|
switch ($status) {
|
|
3 { "Idle" }
|
|
4 { "Printing" }
|
|
5 { "Warming Up" }
|
|
6 { "Paused" }
|
|
7 { "Offline" }
|
|
8 { "Disconnected" }
|
|
default { "Unknown($status)" }
|
|
}
|
|
}
|
|
|
|
function Get-ErrorText($errorState) {
|
|
switch ($errorState) {
|
|
2 { "Paper Jam" }
|
|
3 { "Out of Paper" }
|
|
4 { "Out of Ink/Toner" }
|
|
5 { "Mechanical Failure" }
|
|
default { "Error code: $errorState" }
|
|
}
|
|
}
|
|
|
|
try {
|
|
while ($true) {
|
|
$printers = Get-WmiObject -Class Win32_Printer
|
|
foreach ($printer in $printers) {
|
|
if ($PrinterNames.Count -gt 0 -and ($PrinterNames -notcontains $printer.Name)) { continue }
|
|
$name = $printer.Name
|
|
$status = $printer.PrinterStatus
|
|
$offline = $printer.WorkOffline
|
|
$errorState = $printer.DetectedErrorState
|
|
$statusText = Get-PrinterStatusText $status
|
|
$onlineText = if ($offline) { "Offline" } else { "Online" }
|
|
$statusKey = "$status|$offline"
|
|
if ($lastStatus.ContainsKey($name) -and $lastStatus[$name] -eq $statusKey) { continue }
|
|
$lastStatus[$name] = $statusKey
|
|
$color = if ($offline) { "Red" } elseif ($status -eq 4) { "Yellow" } else { "Green" }
|
|
$time = Get-Date -Format "HH:mm:ss"
|
|
Write-Host "$time ${name}: $statusText ($onlineText)" -ForegroundColor $color
|
|
if ($errorState -and $errorState -ne 0) {
|
|
$errorText = Get-ErrorText $errorState
|
|
Write-Host " └─ Error: $errorText" -ForegroundColor Red
|
|
}
|
|
}
|
|
Start-Sleep -Seconds $IntervalSeconds
|
|
}
|
|
} finally {
|
|
Write-Host "`nMonitoring stopped" -ForegroundColor Yellow
|
|
} |