我有一个包含许多元素的数组$array
,示例如下:
ProfileID : 100
UID : 17
Name : SharePoint
Description : SharePoint Server Description
现在我正在尝试按Name
属性进行过滤,要匹配的字符串是:
$string
SharePoint Policy Assignment
我尝试过:
$array | Where-Object {$_.Name -like "$string"}
no match
$array | Where-Object {$_.Name -like "$string*"}
no match
$array | Where-Object {$_.Name -match "$string"}
no match
使用PowerShell可以吗?我想念什么?
答案 0 :(得分:1)
PowerShell中的-like
运算符用于通配符匹配,因此您需要使用通配符星号*
。
想象一下这种情况,我正在尝试匹配特定的Windows服务。
$svcs = Get-Service | Select-Object -first 15
C:\temp\blog> $svcs
Status Name DisplayName
------ ---- -----------
Stopped AJRouter AllJoyn Router Service
Stopped ALG Application Layer Gateway Service
Running AMD External Ev... AMD External Events Utility
Stopped AppIDSvc Application Identity
Running Appinfo Application Information
Stopped AppMgmt Application Management
Stopped AppReadiness App Readiness
Stopped AppVClient Microsoft App-V Client
Stopped AppXSvc AppX Deployment Service (AppXSVC)
Stopped aspnet_state ASP.NET State Service
Stopped AssignedAccessM... AssignedAccessManager Service
Running AsSysCtrlService ASUS System Control Service
Running AudioEndpointBu... Windows Audio Endpoint Builder
Running Audiosrv Windows Audio
Running AUEPLauncher AMD User Experience Program Launcher
要使用-Like
运算符进行匹配,我必须提供一个通配符,如下所示。
$svcs | Where-Object Name -like App*
Status Name DisplayName
------ ---- -----------
Stopped AppIDSvc Application Identity
Running Appinfo Application Information
Stopped AppMgmt Application Management
Stopped AppReadiness App Readiness
Stopped AppVClient Microsoft App-V Client
Stopped AppXSvc AppX Deployment Service (AppXSVC)
尝试使用通配符进行操作,我敢打赌它会起作用:)
我注意到的另一件事是,您的$string
等于SharePoint Policy Assignment
,但是您要比较的.Name
的列仅为SharePoint
。
答案 1 :(得分:1)
使用已经存储在内存中或很容易容纳的集合,您可以使用 member enumeration 获得更方便的语法,从而使执行速度更快:
@($array.Name) -like $string # returns sub-array of matching elements
-like
,当给定 array 作为LHS时,充当过滤器:仅返回与RHS上的通配符匹配的那些数组元素(也作为数组)。
请注意需要@(...)
以确保$array.Name
是一个数组,因为单元素数组将导致.Name
属性作为标量(单个字符串)返回,在这种情况下-like
将返回 Boolean ({ {1}}或$true
),而不是充当过滤器。
还请注意,许多PowerShell cmdlet 直接支持通配符表达式作为参数值:
以$false
为例,其(暗示)Get-Service
参数支持通配符:
-Name
要确定给定cmdlet参数的通配符支持:
Get-Service *router* # returns all services whose Name contains "router"
应该为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?
,表示支持通配符表达式,但是很遗憾,这不可靠检查参数 description ;在这里,描述部分true
提供了信息。
This GitHub issue描述了问题,并要求使通配符支持的程序可发现性可靠。