Powershell 基于不同输入在AD(Get ADUser)中查找用户的最佳方式

Powershell 基于不同输入在AD(Get ADUser)中查找用户的最佳方式,powershell,filter,split,active-directory,Powershell,Filter,Split,Active Directory,我在寻找你对最佳方式的想法 目标只是基于不同的可能输入找到给定的用户 可能性是: $input = "John,Smith" $input = "John Smith" $input = "John Smith(ext)" $input = "Smith,John" $input = "Smith John" $input = "Smith John(ext)" 我的工作解决方案是: if ($input -like "*(*" ) { $input = $input -replace '\(

我在寻找你对最佳方式的想法

目标只是基于不同的可能输入找到给定的用户

可能性是:

$input = "John,Smith"
$input = "John Smith"
$input = "John Smith(ext)"
$input = "Smith,John"
$input = "Smith John"
$input = "Smith John(ext)"
我的工作解决方案是:

if ($input -like "*(*" ) {
$input = $input -replace '\([^\)]+\)'
}

if ($input -like "*,*"){
$FullName = $input -split "," 
} 
elseif ($input -like "* *"){
$FullName = $input -split " "
} 


get-ADUser -Filter " ( ( (GivenName -like '$($FullName[0])*') -and (SurName -like '$($FullName[1])*') ) -or ( (SurName -like '$($FullName[0])*') -and (GivenName -like '$($FullName[1])*') ) ) "
所以基本上是这样的:

-如果输入包含括号,请删除括号以及括号之间的内容。
-如果输入包含逗号,则拆分该逗号上的字符串。
-如果输入包含空格,请拆分该空格上的字符串。
-获取AdUser,过滤(GivenName和姓氏)或(姓氏和GivenName)
因为我不知道它们的顺序

它工作的很好,但我总是好奇找到最佳的方式


在这种情况下,您有什么建议吗?非常感谢您的输入。

使用
-LDAPFilter
和模糊名称解析(
anr
):

只需将逗号替换为空格,然后删除
(ext)
。变量名
$input
是保留的,因此不应使用:

$name = $name -replace ",", " "
$name = $name -replace "\(ext\)", ""
或链接
-replace
操作员:

$name = $name -replace ",", " " -replace "\(ext\)", ""
搜索将是:

Get-ADUser -LDAPFilter "(anr=$name)"

伙计,这很好。我不知道anr,我使用了这个解决方案,但我保留了我的正则表达式“([^)]+”,因为EXT不能保证在那里。非常感谢!:)这里描述了模棱两可的名称解析:关于这一点有两件事。1.
$input
是一个保留变量名。应该使用其他东西(是的,我知道你复制了OPs代码)。2.你可以用链式替换把它连在一条线上
$userChoice=$userChoice-replace“,“-replace”\(ext\)”
。除此之外,我今天学到了关于anr的知识,这真是太棒了。
$input
一直萦绕在我的脑海中。编辑了这篇文章。谢谢Matt,是的,输入只是一个例子,但实际代码有不同的优点
Get-ADUser -LDAPFilter "(anr=$name)"