SimonS
SimonS

Reputation: 1973

.contains() vs -contains, one returns true, other returns false

I have a Hash Table like this:

$Path = @{
    "BM"    = "\\srv\xy"
    "BB4-L" = "\\srv\xy"
    "BB4-R" = "\\srv\xy"
    "HSB"   = "\\srv\xy"
    "IB"    = "\\srv\xy"
    "LM1"   = "\\srv\xy"
    "LM2"   = "\\srv\xy"
    "sis"   = "\\srv\xy"
}

my $env:username is sis. Why does .contains() and -contains something different?

PS Z:\Powershell-Scripts\Functions> $Path -contains $env:username
False

PS Z:\Powershell-Scripts\Functions> $Path.contains($env:username)
True

I always like to go with the PowerShell Syntax if possible, but I can't in this case, since -contains would return false.

How are .contains() and -contains different?

Upvotes: 0

Views: 1014

Answers (3)

Steve Gray
Steve Gray

Reputation: 31

I got the code to work by changing from hashtable.containskey to -contains. In the following code snippit, i commented our the line containing .containsKey($UserIDFromAD) and added the line containing $UserIDsFromFile.keys -contains $UserIDFromAD. The code now works as expected.

So, whats the difference between .containskey and -contains?

#if ($UserIDsFromFile.containsKey($UserIDFromAD)){ #If the UserID is in Yesterdays list ignore it.
if ($UserIDsFromFile.keys -contains $UserIDFromAD){ #If the UserID is in Yesterdays list ignore it.

Upvotes: 0

Paweł Dyl
Paweł Dyl

Reputation: 9143

$Path is a System.Collections.Hashtable. You can also read in documentation that:

When the test value is a collection, the Contains operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.

Each item in hashtable is System.Collections.DictionaryEntry. You are comparing it to string. Since types do not match, references do not match as well. Contains(System.Object key) and ContainsKey(System.Object key) use keys to test. To be consistent in comparisons you should write:

$Path.Keys -contains $env:username

Upvotes: 2

Kirill Pashkov
Kirill Pashkov

Reputation: 3226

From MS documentation:

-Contains
      Description: Containment operator. Tells whether a collection of reference
      values includes a single test value. Always returns a Boolean value. Returns TRUE
      only when the test value exactly matches at least one of the reference values. 

.Contains() Method is one of the methods of a String object that supports substring hence why you get True when you run $Path.Contains($env:username)

Upvotes: 1

Related Questions