70

In PowerShell I have an array of string objects, and I have an object that contains string objects. In Java you can do a .equals(aObject) to test if the string values match, whereas doing a == test if the two objects refer to the same location in memory.

How do I run an equivalent .equals(aObject) in powershell?

I'm doing this:

$arrayOfStrings[0].Title -matches $myObject.item(0).Title

These both have the exact same string values, but I get a return value of false. Any suggestions?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nullByteMe
  • 6,141
  • 13
  • 62
  • 99

2 Answers2

92

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

Sudhanshu Mishra
  • 6,523
  • 2
  • 59
  • 76
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • 2
    Casting to string worked best for me: `$a = cat ./text.txt` `$b = cat ./text2.txt` `[string]$a -eq [string]$b` returns false because the files are different – Kellen Stuart Feb 21 '17 at 21:05
67

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

alroc
  • 27,574
  • 6
  • 51
  • 97