【问题标题】:Using Select-Object and Where-Object in same sentence with PowerShell使用 PowerShell 在同一个句子中使用 Select-Object 和 Where-Object
【发布时间】:2020-01-09 01:22:15
【问题描述】:

我是使用 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 多行。

【问题讨论】:

    标签: powershell active-directory select-object


    【解决方案1】:

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

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

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

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

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

    您可以在the documentation 中阅读有关-Join 的信息。

    但是您也不能在使用-Filter 的同时使用-Identity 参数($_ 被映射到的参数)。因此,您必须在过滤器中包含用户名(或 SamAccountName)。

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

    $csv.Username | ForEach-Object {
        Get-ADUser -Filter "SamAccountName -eq '$_' -and (Department -like '$($IS -Join "' -or Department -like '")')" -Properties Department | Select-Object SamAccountName,Department
    }
    

    【讨论】:

    • 我确实工作过,由于“描述”不正确,我对您的答案进行了一些修改。
    • @BryanArreola 哎呀,对不起。我读得太快了。有一个属性叫做Description,它不是你要找的那个。
    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 2011-11-03
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2016-05-21
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多