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
Never use a script block ({ ... }
) as the -Filter
argument - the -Filter
parameter's type is [string]
- construct your filter as a string.
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.
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'" ...
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)'"