Home > Back-end >  Powershell .contains() check without casesensitive
Powershell .contains() check without casesensitive

Time:10-27

I'm having a larger foreach loop code but need to get below code executed without casesensitive.

Below code snippet returns false, how can I ignore the casesensitive .contains() and the condition as true?

$a='aa0855' $b='AA0855 Sample' $b.Contains($a)

Expected value is true. Above code is tried with 2 variables and it returns false.

CodePudding user response:

The .Contains() .NET string method is indeed case-sensitive - invariably in Windows PowerShell, and by default in PowerShell (Core) 7 .

Thus, in PowerShell (Core) 7 you can do:

# PS 7  only
# -> $true
$a='aa0855'; $b='AA0855 Sample'; $b.Contains($a, 'InvariantCultureIgnoreCase')

The second .Contains() argument is converted to an enumeration value of type StringComparison; InvariantCultureIgnoreCase is the same value that PowerShell's operators use by default, i.e. a case-insensitive comparison that is culture-neutral (i.e. performed in the context of the invariant culture).


In Windows PowerShell you have two options, using PowerShell operators, which are case-insensitive by default:

$a='aa0855'; $b='AA0855 Sample'; $b -like "*$a*" 

If $a could contain literal * and ? characters:

$a='aa0855'; $b='AA0855 Sample'; $b -like ('*{0}*' -f [WildcardPattern]::Escape($a)) 
$a='aa0855'; $b='AA0855 Sample'; $b -match $a

If $a contains characters that are metacharacters in the context of a regex, such as ., they must be escaped, either individually with \, or, more simply, in the entire string with [regex]::Escape()`:

$a='aa0855'; $b='AA0855 Sample'; $b -match [regex]::Escape($a)
  • Related