为了补充FoxDeploy 的有用答案:
对于已经在内存中或很容易适应的集合,您可以使用成员枚举来获得更方便的语法,从而加快执行速度:
@($array.Name) -like $string # returns sub-array of matching elements
-like
,当给定一个数组作为 LHS 时,充当过滤器:仅返回与 RHS 上的通配符表达式匹配的那些数组元素(也作为数组)。
请注意需要@(...)
确保它$array.Name
是一个数组,因为单元素数组会导致.Name
属性作为标量(单个字符串)返回,在这种情况下-like
将返回布尔值($true
或$false
)而不是充当过滤器。
另请注意,许多 PowerShell cmdlet直接支持通配符表达式作为参数值:
举Get-Service
个例子,它的(隐含的)-Name
参数支持通配符:
Get-Service *router* # returns all services whose Name contains "router"
要确定给定 cmdlet 参数的通配符支持:
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
它应该是表示支持通配符表达式的Accept wildcard characters?
值,但是不幸的是,这并不可靠,因此还要检查参数说明;在这里,描述部分提供了信息。此 GitHub 问题描述了该问题,并要求使通配符支持的编程可发现性可靠。true
Wildcards are permitted