powershell contains not working

20,398

Contains is meant to work against arrays. Consider the following examples

PS C:\Users\Cameron> 1,2,3 -contains 1
True

PS C:\Users\Cameron> "123" -contains 1
False

PS C:\Users\Cameron> "123" -contains 123
True

If you are looking to see if a string contains a text pattern then you have a few options. The first 2 would be -match operator or the .Contains() string method

  1. -match would be one of the simpler examples to use in and If statement. Note: -Match supports .Net regular expressions so be sure you don't put in any special characters as you might not get the results you expect.

    PS C:\Users\Cameron> "Matt" -match "m"
    True
    
    PS C:\Users\Cameron> "Matt" -match "."
    True
    

    -match is not case sensitive by default so the first example above returns True. The second example is looking to match any character which is what . represents in regex which is why it returns True as well.

  2. .Contains(): -match is great but for simple strings you can ....

    "123".Contains("2")
    True
    
    "123".Contains(".")
    False
    

    Note that .Contains() is case sensitive

    "asdf".Contains('F')
    False
    
    "asdf".Contains('f')
    True
    
Share:
20,398
Bernie
Author by

Bernie

Updated on August 15, 2020

Comments

  • Bernie
    Bernie over 3 years

    I am trying filter by the name of each share using $Share.Name. However, when I try to use -contains in the if statement below, I get no results.

    The result I want should be ADMIN$ - C:\ADMIN$

    I am working my way to being able to have a variable like: $ExcludeShares = "ADMIN$" and filtering based on if the $String.Name is in $ExcludeShares

    I am open to ideas on other ways to filter this.

    Thanks in advance!

    function GetAllUsedShares{
        [psobject]$Shares = Get-WmiObject -Class win32_share
        Foreach($Share in $Shares){
            $name = [string]$Share.Name
            if ($name -contains 'admin'){
                Write-Host $Share.Name - $Share.Path
            }
    
        }   
    }
    
  • js2010
    js2010 over 4 years
    Bizarrely .contains() works like -contains on arrays.