To complement FoxDeploy's helpful answer:
With collections that are already are in memory or easily fit, you can use member-access enumeration for a more convenient syntax that also results in much faster execution:
@($array.Name) -like $string # returns sub-array of matching elements
-like
, when given an array as the LHS, acts as a filter: only those array elements that match the wildcard expression on the RHS are returned (also as an array).
Note the need for @(...)
to ensure that $array.Name
is an array, because a single-element array would result in the .Name
property getting returned as a scalar (a single string), in which case -like
would return a Boolean ($true
or $false
) rather than acting as a filter.
Also note that many PowerShell cmdlets directly support wildcard expressions as parameter values:
Taking Get-Service
as an example, its (implied) -Name
parameter supports wildcards:
Get-Service *router* # returns all services whose Name contains "router"
To determine a given cmdlet parameter's wildcard support:
PS> Get-Help Get-Service -Parameter Name
-Name <String[]>
Specifies the service names of services to be retrieved. Wildcards are permitted. By default, this cmdlet gets all of the services on the computer.
Required? false
Position? 1
Default value None
Accept pipeline input? True (ByPropertyName, ByValue)
Accept wildcard characters? false
It should be the Accept wildcard characters?
value being true
that indicates support for wildcard expressions, however, this is unfortunately not reliable, so also check the parameter description; here, the descriptin part Wildcards are permitted
provides the information.
GitHub issue #4716 describes the problem and asks to make the programmatic discoverability of wildcard support reliable.