CEGRD
CEGRD

Reputation: 7915

What is the difference between -contains vs .contains in powershell script?

What is the difference between .contains and -contains? One seems case sensitive while the other one is not.

PS C:\WINDOWS\system32> ("jack", "john", "jill").contains("Jill")
False


PS C:\WINDOWS\system32> "jack", "john", "jill" -contains "Jill"
True

Why is there such a discrepancy?

Upvotes: 7

Views: 15340

Answers (2)

Ranadip Dutta
Ranadip Dutta

Reputation: 9123

Both are very different in actual.

$str = "abcde"

$str -contains "abcd" 
False

$str.Contains("abcd") 
True

Why this difference?

Because

-Contains is a Containment operator as per MS. 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.It must be one of the elements include(contains) in the array not a substring of a string element

Contains() Method is one of the methods of string object that supports substring hence why you get True when you run $str.Contains("abcd")

Hope it helps.

Upvotes: 4

AdminOfThings
AdminOfThings

Reputation: 25001

The -Contains operator compares one object against a collection. It returns true if that entire value exists as an item in a collection. It is case-insensitive and is not limited to strings. -CContains is the case-sensitive version. The .Contains() method is a .NET method from the String class. It compares a substring against a string (case-sensitive by default).

Your first example could be manipulated to achieve the desired results if you convert your array into a string because jill will be a substring within the larger string.

("jack","jill","john" -join ",").Contains("jill")
True

See About_Comparison_Operators for details and examples of using -Contains. See String.Contains Method for an explanation of the .Contains method.

Upvotes: 12

Related Questions