部分字符串混淆的PowerShell比较

PowerShell comparison of partial string confusion

我在一个数组中有一组部分职称,我试图将其与 Active Directory (AD) 中某人的完整职称进行比较。 -like-match 以及所有其他的都不起作用。

[string[]]$Titles =@('genetic','medic','nurs','optome','perfusion','pharm','phys')

($titles -like $user.Title) - nope
($user.title -contains $titles) - nope
($Titles.Contains($user.title)) - nope

我需要一个用户标题,"Physician",以匹配 "phys"。为什么这不起作用?

要执行您(似乎)想要的操作,请迭代 ("loop") $Titles 中的每个标题并将 $User.Title 属性 与每个单独的部分标题进行比较,然后查看是否有任何返回 $true:

foreach($User in Get-ADUser -Filter * -Properties Title){
    $TitleFound = @($Titles |ForEach-Object {$User.Title -like "$_*"} ) -contains $true
    if($TitleFound){
        Do-Stuff
    }
}

话虽如此,您可能希望使用部分字符串来构建 LDAP Filter 字符串,这样域控制器就可以负责过滤而不是返回所有用户。

I LDAP 搜索过滤器语法,您的查询将如下所示:

(|(title=genetic*)(title=medic*)(title=nurs*)(title=optome*)(title=perfusion*)(title=pharm*)(title=phys*))

您可以使用 ForEach-Object:

从您的字符串数组生成它
# The | prefix means "or", as in "if any of these statements are true", return the object
$FilterTemplate = '(|{0})' 

# This will be the comparison statements inside the filter
$FilterCriteria = $Titles |Foreach-Object { '(title={0}*)' -f $_ }

# Now put it all together
$LDAPFilter = $FilterTemplate -f -join($FilterCriteria)

# And retrieve the users:
$MedicalStaff = Get-ADUser -LDAPFilter $LDAPFilter -Properties Title