Search code examples
stringkeymatchhashtablepowershell-2.0

Powershell 2.0: how to -match or -like a string in hash table keys


For Powershell 2.0:

I have a hash table with several strings as keys. Unlike @{}.containskey, is it possible to find a key (e.g., "examplekey") using wildcards (e.g., "*xampl*")?

I managed to accomplish what I wanted making a list of the keys and using Where-Object as a filter. But is there a simpler way to do it? I think this method is specially bad when I'm adding new keys, because I need to recreate the list everytime.


Solution

  • Use .Keys property and -like or -notlike operators that return an array of keys (or a single key):

    if ($hash.keys -notlike '*xampl*') {
        $hash.example = 1
    }
    

    Store the keys in an array for multiple checks:

    $keys = $hash.keys
    if ($keys -notlike '*xampl*') {
        $hash.example = 1
    }
    if ($keys -notlike '*foo*') {
        $hash.example = 1
    }
    

    Chain the comparisons:

    if ($hash.keys -notlike '*xampl*' -notlike '*123*') {
        $hash.example = 1
    }
    

    Or use regexp in case there are lots of keys and you want to perform lots of checks:

    if ($hash.keys -join "`n" -match '(?mi)xampl|foo|bar|^herp\d+|\wDerp$|^and$|\bso\b|on') {
       echo 'Already present'
    } else {
       $hash.foo123 = 'bar'
       # ......
    }
    

    (?mi) means multiline case-insensitive mode: each key is tested individually.