Passing string in Get-ADUser filter parameter causes error - property not found in pscustomobject

后端 未结 3 1961
梦如初夏
梦如初夏 2020-11-28 17:08

I\'m trying to create a new Active Directory user, but first I verify that the user doesn\'t exist already with Get-ADUser. I import the user data from our HR d

相关标签:
3条回答
  • 2020-11-28 17:31
    • Never use a script block ({ ... }) as the -Filter argument - the -Filter parameter's type is [string] - construct your filter as a string.

      • BenH's answer shows how to do that.
    • While seemingly convenient, using a script block only works in very limited scenarios and causes confusion when it doesn't work - such as when involving property access, as in this case.

    For more information, see this answer of mine.

    0 讨论(0)
  • 2020-11-28 17:33

    The BNF for filter query strings does not allow expressions as the second operand in a comparison, only values (emphasis mine):

    Syntax:
    The following syntax uses Backus-Naur form to show how to use the PowerShell Expression Language for this parameter.

    <filter> ::= "{" <FilterComponentList> "}"
    <FilterComponentList> ::= <FilterComponent> | <FilterComponent> <JoinOperator> <FilterComponent> | <NotOperator> <FilterComponent>
    <FilterComponent> ::= <attr> <FilterOperator> <value> | "(" <FilterComponent> ")"
    <FilterOperator> ::= "-eq" | "-le" | "-ge" | "-ne" | "-lt" | "-gt"| "-approx" | "-bor" | "-band" | "-recursivematch" | "-like" | "-notlike"
    <JoinOperator> ::= "-and" | "-or"
    <NotOperator> ::= "-not"
    <attr> ::= <PropertyName> | <LDAPDisplayName of the attribute>
    <value>::= <compare this value with an <attr> by using the specified <FilterOperator>>

    Put the value of the property you want to compare against in a variable and use that variable in the comparison. You may also want to define the filter as an actual string, if only for clarity (despite what it looks like the filter is not a scriptblock).

    $upn = $newUser.UPN
    $exists = Get-ADUser -Filter "UserPrincipalName -eq '$upn'" ...
    
    0 讨论(0)
  • 2020-11-28 17:33

    Expressions can inside the filter block of a Get-ADUser but they need to be properly wrapped with quotes.

    Get-ADUser -Filter "UserPrincipalName -eq '$($newUser.UPN)'"
    
    0 讨论(0)
提交回复
热议问题