Google

2014-01-09

Finding and dealing with a special char in PowerShell

Recently I ran into an issue while doing regex on Bios Serial Numbers. A couple of machines returned a special character as their serial number when I ran the following command

(Get-WmiObject Win32_Bios) .SerialNumber

�����

Not sure if it will show up fine on your computer but it looks like a black diamond shape with question mark in it.

For my purpose, I needed to eliminate such computers from my results, so naturally I wanted to be able to match them in my regular expression.

The problem was that I had no idea how to produce it in my regex.
I knew I could have produced any character using this

[char]'CharCodeGoesHere'

But  how do I find the char code? Here is how:

I copied the first '?' character and then pasted it between the single quotes (could have been double quotes but in general if you do not want something to be evaluated, avoid double quotes) below in PowerShell

PS D:\> [int][char]'�'
65533

So I could reproduce the weird character by dropping [int]

PS D:\> [char]65533


This meant that I could now use it in regular expression like this:

PS D:\>(Get-WmiObject Win32_Bios) .SerialNumber -match "$([char]65533)"
True

While we are at it, here are a couple of valid and invalid ways to do this comparison

PS D:\> '�' -match "$([char]65533)"
True

PS D:\> "�" -match [char]65533
True

PS D:\> '�' -match [char]65533
True

PS D:\> '�' -match '[char]65533'  (Included this because single quote some times trip people. PowerShell does not evaluate the stuff inside single quotes.

PS D:\> � -match "$([char]65533)"
� : The term '�' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ � -match "$([char]65533)"
+ ~
    + CategoryInfo          : ObjectNotFound: (�:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

In the last example above, Left side of -match operator is not enclosed within any quotes and therefore an error is generated. Error is quite self explanatory.

No comments: