PowerShell比较部分字符串混淆

时间:2015-11-12 21:33:48

标签: powershell conditional

我在一个数组中有一组部分职位,我试图在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"。为什么这不起作用?

1 个答案:

答案 0 :(得分:2)

执行您(似乎)想要的操作,对$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字符串,这样域控制器就可以处理过滤而不是返回所有用户。

我是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