0

Trying to write a script to remove all network printers from a system but leave the other printers / fax alone.

$Printer = Get-WMIObject Win32_Printer | Select-Object ServerName, ShareName 

to get the values for $Printer but cannot get it to change to uppercase. @{ServerName=\\HBMN-Vbranch; ShareName=HBMN-P5} is returned but I am trying to do if ($Printer -Like "*\\HBMN-VBRANCH*") and it never finds the lower case or mixed case.

If I try to do $($Printer.ToString().ToUpper()) no value is returned. If I try $Printer.ToUpper() method is not found.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • As an aside: your problem is unrelated to character _case_: PowerShell's string operations are case-_insensitive_ by default. – mklement0 Feb 21 '19 at 21:48

2 Answers2

1

.toUpper() is a method for strings. So convert that output to a string using out-string:

($printer.SystemName|out-string).toUpper()
  • 1
    I assume you meant `.ServerName`, not `.SystemName`, which already _is_ a string, so you can just call `.ToUpper()` directly on it. More importantly: Not only is piping to `Out-String` a very inefficient way to convert objects to strings (though sometimes it is the right tool), it also _appends a newline_ to something that's already a string, which is undesired. Finally, PowerShell's operators such as `-like` are case-_insensitive_, so there's no need for case conversion. – mklement0 Feb 21 '19 at 21:46
1

Calling ToString() on $Printer does not convert the custom object (PSCustomObject) to string, that's your basic problem. This should work:

$Printer.ServerName.ToUpper()

But if you don't need the share name in the custom object, just get the server name as string:

$serverName = Get-WMIObject Win32_Printer | Select-Object -ExpandProperty ServerName

Furthermore, your comparison should use the server name, not the $Printer object:

if ($Printer.ServerName -like "*HBMN-VBRANCH*") 
mklement0
  • 382,024
  • 64
  • 607
  • 775
Ben Richards
  • 3,437
  • 1
  • 14
  • 18