Skip to content

Instantly share code, notes, and snippets.

@rstolpe
Last active February 16, 2024 14:43
Show Gist options
  • Save rstolpe/da8a18b018ebaef2ba686fdaf305748c to your computer and use it in GitHub Desktop.
Save rstolpe/da8a18b018ebaef2ba686fdaf305748c to your computer and use it in GitHub Desktop.
Helping with deleting printers
Function Remove-PrintersFromComputers {
<#
Remove-PrintersFromComputers -PrinterToExclude "Printer1, Printer2, *Printer4*" -ComputerName "Computer1"
#>
[CmdletBinding()]
Param(
[String]$ComputerName = "localhost",
[String]$PrinterToExclude
)
#Fill out Needed modules here
$NeededModules = "PrintManagement, microsoft.powershell.management"
# Here you need to fill out the register path.
$RegPath = ""
foreach ($module in $NeededModules.Split(",").Trim()) {
Get-Module $module
}
Foreach ($Computer in $ComputerName.Split(",").Trim()) {
Write-Host "Removing printers from $Computer..."
try {
Get-Printer -ComputerName $Computer | Where-Object { $_.Name -notlike $PrinterToExclude -and $_.Network -eq "True" } | Remove-Printer
}
catch {
Write-Error "$($PSItem.Exception)"
continue
}
Invoke-Command -ComputerName $Computer -Scriptblock {
Param(
$RegPath,
$PrinterToExclude
)
Try {
Get-ItemProperty -Path $RegPath | Where-Object { $_.Name -notlike $PrinterToExclude -and $_.Network -eq "True" } | Remove-ItemProperty
}
catch {
Write-Error "$($PSItem.Exception)"
continue
}
} -ArgumentList $RegPath, $PrinterToExclude
try {
Write-Host "Restarting spooler service..."
Restart-Service -ComputerName $Computer -Name 'Spooler'
do {
Write-Host 'Waiting for spooler service to restart...'
Start-Sleep -s 1
} while (Get-Service -ComputerName $Computer -Name spooler -ErrorAction SilentlyContinue)
Write-Host "Spooler is now restarted!" -ForegroundColor Green
}
catch {
Write-Error "$($PSItem.Exception)"
continue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment