0

Working on a script to delete all but the highest "Copy" printer (Microsoft and its infinite helpfulness creates "Copy" printers every time one of my remote users unplugs/plugs in a printer) on Windows 7 PCs.

I have two different printer names which get many "copies" made due to this problem. In one case, it's easy because I want to delete all of the "Copy" printers, but leave the original printer - the one that doesn't have "Copy" in its name. I do that by first clearing all print jobs (will not delete the printer if there's an existing job sitting in the queue), then delete all the "POS Lexmark (Copy)" printers -

Get-WmiObject Win32_Printer | ForEach-Object {$_.CancelAllJobs()}

Get-WmiObject Win32_Printer -Filter "name LIKE '%POS Lexmark (Copy%'" | ForEach-Object {$_.Delete()}

Works great. In the second case, I want to keep the highest "Copy" number printer - i.e. if there are 12 "Copy" printers, I want to keep the "Lexmark Universal PS3 (Copy 12)" printer, but delete all the rest. I do have a natural sort function line:

$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }

Which I can use to sort all the "Copy" printers in this case, but this

Get-WmiObject Win32_Printer -Filter "name LIKE '%PS3 (Copy%'" | Sort-Object $ToNatural | Select-Object | ForEach-Object {$_.Delete()}

won't work because I still need to keep whatever that highest number printer is after the sort. I'm a Powershell newbie, so any help would be appreciated since a Google search has not turned anything up for me yet.

Thank you

BigRedEO
  • 807
  • 4
  • 13
  • 33

1 Answers1

1

Could you place your sorted results into a variable, and select-object all but the last (highest) result?

$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
$sorted = Get-WmiObject Win32_Printer -Filter "name LIKE '%PS3 (Copy%'" | Sort-Object $ToNatural
$sorted | Select-Object -First ($sorted.Count-1) | ForEach-Object {$_.Delete()}
xXhRQ8sD2L7Z
  • 1,686
  • 1
  • 14
  • 16
  • Yes! This worked. Thank you very much. Been researching that for quite a while and could never get the Count to work. – BigRedEO Feb 04 '16 at 15:49