Author Posts

January 27, 2014 at 1:08 pm

I'm trying to compare two values. If they match, I need to say they match. If they do not match, I need to say they do not match. Simple enough, however, I have one character that is throwing this all off. Frustrating because I know the answer is probably simple.

Value 1 = 6d2c6181-cc86-4075-ab7e-a5f7250b6ae8

Value 2 = {6d2c6181-cc86-4075-ab7e-a5f7250b6ae8}

For what I'm doing, these two values do match. I need to forget the { is there. In this case, it doesn't matter. That is the part I'm choking on. What comparison operator would I use in this case? I can't use equal, because to PowerShell, they do not equal each other. I thought -contains would do the trick, but it's not. I'm using the comparison in an If Else cmdlet, if that helps.

January 27, 2014 at 4:36 pm

Are both of these values actually strings? When PowerShell displays objects as text, those curly braces sometimes indicate a property that is a collection.

Assuming they're both strings, in this specific case, I'd just take advantage of the System.Guid type, which can handle parsing both of those forms:

$value1 = '6d2c6181-cc86-4075-ab7e-a5f7250b6ae8'
$value2 = '{6d2c6181-cc86-4075-ab7e-a5f7250b6ae8}'

if ([guid]$value1 -eq [guid]$value2)
{
    'Equal'
}
else
{
    'Not equal'
}

For other strings that don't correspond to a type like that, you'd have to do some work yourself to strip out the unimportant characters. For instance, you could remove all characters that aren't hexadecimal digits before comparing:

$value1 = '6d2c6181-cc86-4075-ab7e-a5f7250b6ae8'
$value2 = '{6d2c6181-cc86-4075-ab7e-a5f7250b6ae8}'

if ($value1 -replace '[^a-f0-9]' -eq $value2 -replace '[^a-f0-9]')
{
    'Equal'
}
else
{
    'Not equal'
}

January 27, 2014 at 6:27 pm

Thanks Dave. If I could buy you a beer, I would. Here is a virtual one!

I had to modify my query a little, but it's working great.