0

我是使用 PowerShell 的新手,我正在尝试从 Active Directory 中选择一些类似于字符串的字段,让我解释一下:

到目前为止,这是我的代码:

$csv = Import-Csv C:\Users\barreola\Desktop\test_AD.csv

$IS = @(
'*601*',
'*609*',
'*602*',
'*608*',
'*610*',
'*611*',
'*1212*',
'*603*',
'*604*'
)


$csv.Username | ForEach-Object {
    Get-ADUser $_ -Properties Department | Select-Object SamAccountName,Department
}

至此,这检索到了预期的数据,如下图

SamAccountName Department                              
-------------- ----------                              
user1          First floor department (0601)
user2          Second floor department (0609)                   
user3          Second floor department (0609)                   
user4          Second floor department (0609)                   
user5          Third floor department (0604)              
user6          Fourth floor department (0707)      
user7          Fifth floor department (0500)                  
user8          Sixth floor department (1306)   
user9          First floor department (0601)

但我希望 PowerShell 只显示包含在 中的内容$IS,例如

Get-ADUser $_ -Properties Department | Select-Object SamAccountName,Department Where-Object {Department -like $IS}

预期的输出将是

SamAccountName Department                              
-------------- ----------                              
user1          First floor department (0601)
user2          Second floor department (0609)                   
user3          Second floor department (0609)                   
user4          Second floor department (0609)                   
user5          Third floor department (0604)   
user9          First floor department (0601)

注意:.csv文件包含 700,000+ 行。

4

1 回答 1

3

Where-Object 可以做到这一点,但这不是最好的方法。您使用的方式Get-ADUser将检索您域中的每个用户。那是需要最长的部分。因此,您不想检索比必须检索更多的用户,因为那只会浪费您的时间。

相反,请使用-Filter参数,Get-ADUser以便您只向 AD 询问您想要的用户。在您的情况下,您需要这样的字符串:

Department -like *601*' -or Department -like '*609*' -or etc.

您可以通过执行以下操作从数组中获取类似的字符串:

"Department -like '$($IS -Join "' -or Department -like '")'"

-Join您可以在文档中阅读有关。

-Identity但是您也不能$_在使用-Filter. 因此,您必须SamAccountName在过滤器中包含用户名(或)。

放在一起,这就是它的样子:

$csv.Username | ForEach-Object {
    Get-ADUser -Filter "SamAccountName -eq '$_' -and (Department -like '$($IS -Join "' -or Department -like '")')" -Properties Department | Select-Object SamAccountName,Department
}
于 2020-01-09T02:27:17.847 回答