powershellscriptingwindows-scripting

How to match multiple strings with Where-Object/Wildcards?


I'm asked to extract commands using Get-Command, where the verb is one of get, set or convertTo and the noun starts with any of C, X or V.

This is what I have so far:

Get-Command | ?{$_ -like "set[-][CXV]*"} #Prints all commands that start with Set

I am struggling to search for multiple verbs that are either set, get, or ConvertTo. I have attempted several different methods but to no avail.


Solution

  • You started off correctly, however, -like lets you match only wildcard patterns whereas -match let you match regex patterns and your regex just needs a little tweaking:

    Get-Command | ?{$_ -match "((^set)|(^get)|(^convertto))-[CXV]+"}
    

    This can be further shortened to:

    Get-Command | ?{$_ -match "((^[sg]et)|(^convertto))-[CXV]+"}
    

    If you want a sorted output of the commands:

    Get-Command | ?{$_ -match "((^[sg]et)|(^convertto))-[CXV]+"} | Sort
    

    Ref: About Comparison Operators