【问题标题】:Can you use -Filter on Get-ADUser to filter out empty fields?您可以在 Get-ADUser 上使用 -Filter 来过滤掉空字段吗?
【发布时间】:2018-06-14 23:44:34
【问题描述】:

在从 Active Directory 抓取数据然后将其插入 SQL 表时,有没有办法过滤掉空字段?当我在Get-ADUser 上使用-Filter 时,我认为这不是正确的语法。

它失败了

输入对象不能绑定到命令的任何参数,因为命令不接受管道输入,或者输入及其属性不匹配任何接受管道输入的参数

$ADARRAY = (Get-ADGroupMember -Identity "Domain Users" -Recursive |
           Get-ADUser -Filter {-not (Mail -like "*")} -Properties Mail)

foreach($OBJECT in $ADARRAY) {
    $NAME = $OBJECT.Name 
    $USER = $OBJECT.SamAccountName
    $EMAIL = $OBJECT.Mail

    $INSERT = "INSERT $TABLE VALUES ('$USER','$EMAIL', '$NAME')"
    $SQL.CommandText = $INSERT 

    $SQL.ExecuteNonQuery()
}

$SQLCON.Close()

【问题讨论】:

    标签: powershell active-directory


    【解决方案1】:

    您收到该错误消息是因为 Get-ADUser 可以要么从管道读取输入使用参数 -Filter。如果您查看documentation,您会发现该 cmdlet 有 3 个参数集:

    Get-ADUser
       [-AuthType <ADAuthType>]
       [-Credential <PSCredential>]
       -Filter <String>
       [-Properties <String[]>]
       [-ResultPageSize <Int32>]
       [-ResultSetSize <Int32>]
       [-SearchBase <String>]
       [-SearchScope <ADSearchScope>]
       [-Server <String>]
       [<CommonParameters>]
    
    Get-ADUser
       [-AuthType <ADAuthType>]
       [-Credential <PSCredential>]
       [-Identity] <ADUser>
       [-Partition <String>]
       [-Properties <String[]>]
       [-Server <String>]
       [<CommonParameters>]
    
    Get-ADUser
       [-AuthType <ADAuthType>]
       [-Credential <PSCredential>]
       -LDAPFilter <String>
       [-Properties <String[]>]
       [-ResultPageSize <Int32>]
       [-ResultSetSize <Int32>]
       [-SearchBase <String>]
       [-SearchScope <ADSearchScope>]
       [-Server <String>]
       [<CommonParameters>]
    

    其中第二个将用于从Get-ADGroupMember 读取管道输入(通过参数-Identity),但是在指定参数-Filter 时,您将强制使用第一个,它不接受您的管道输入。

    此外,从您的代码来看,您实际上希望 具有 mail 属性的用户对象。

    使用像这样的Where-Object 过滤器,代码应该做你想做的事:

    $ADARRAY = Get-ADGroupMember -Identity 'Domain Users' -Recursive |
               Get-ADUser -Properties Mail |
               Where-Object { $_.Mail -like '*' }
    

    如果您确实想要具有mail 属性的用户对象,请将条件$_.Mail -like '*' 更改为$_.Mail -notlike '*'

    【讨论】:

      【解决方案2】:

      您已经接近了,但 Filter 采用过滤字符串而不是脚本块(尝试 Get-Help Get-ADUser)。

      这应该可以满足您的需求:

      Get-ADUser -Filter "Mail -notlike '*'"
      

      This page explains more on the filter syntax for AD.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        • 2017-02-06
        相关资源
        最近更新 更多