ninja-one/old/remove-jread02-printers.ps1
|
#Requires -Version 5.1 <# .DESCRIPTION Removes all printers containing 'jre-ad02' from the system. #> [CmdletBinding()] param ( [Parameter()] [Switch]$Restart = [System.Convert]::ToBoolean($env:forceRestart) ) begin { # Check for required PowerShell version (7+) if (!($PSVersionTable.PSVersion.Major -ge 7)) { try { # Install PowerShell 7 if missing if (!(Test-Path "$env:SystemDrive\Program Files\PowerShell\7")) { Write-Output 'Installing PowerShell version 7...' Invoke-Expression "& { $( Invoke-RestMethod https://aka.ms/install-powershell.ps1 ) } -UseMSI -Quiet" } # Refresh PATH $env:Path = [System.Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path', 'User') # Restart script in PowerShell 7 pwsh -File "`"$PSCommandPath`"" @PSBoundParameters } catch { Write-Output 'PowerShell 7 was not installed. Update PowerShell and try again: $_' throw $Error } finally { exit $LASTEXITCODE } } else { $PSStyle.OutputRendering = 'PlainText' } } process { try { # Ensure the print spooler service is running $spooler = Get-Service -Name "spooler" if ($spooler.Status -ne 'Running') { Start-Service -Name "spooler" -ErrorAction SilentlyContinue Write-Host "Starting the print spooler service..." # Wait for up to 1 minute for the spooler service to start $timeout = 60 $interval = 5 $elapsed = 0 while ($spooler.Status -ne 'Running' -and $elapsed -lt $timeout) { Start-Sleep -Seconds $interval $spooler = Get-Service -Name "spooler" $elapsed += $interval } if ($spooler.Status -ne 'Running') { Write-Host "[Error] Print spooler service failed to start." exit 1 } Write-Host "Print spooler service is running." } # get a list of all printers installed on the computer $printers = Get-Printer -ErrorAction SilentlyContinue # loop through all printers and remove the printer if it contains 'jre-ad02' (case insensitive) foreach ($printer in $printers) { if ($printer.Name -like "*jre-ad02*") { Write-Host "Removing printer $($printer.Name)" Remove-Printer -Name $printer.Name -ErrorAction SilentlyContinue } } } catch { Write-Error $_ Write-Host "[Error] Failed to remove jre-ad02 printers." exit 1 } exit 0 } end { } |