Can you please let me know what is wrong with this code?
$SearchUser.Add_Click(
{
$Output.text =
Get-AdUser -Filter "Surname -like $entry" |
select name, samaccountname
}
)
I keep getting this error:
Get-aduser : Error parsing query: 'Surname -like rondon' Error Message: 'syntax error' at position: '15'.
At line:50 char:11
+ $search = Get-aduser -Filter "Surname -like $entry" | select name, sa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingExcepti
on,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Filter works standalone in powershell but not via the form
tl;dr
Your Get-ADUser
-Filter
argument isn't well-formed; use:
Either: "Surname -like `"$entry`""
(up-front string interpolation, requires embedded quoting)
"..."
literals; embedding expressions or commands requires enclosure in $(...)
, the subexpression operator, e.g. "Surname -like `"$($entry.Text)`""
or"Surname -like `"$(Get-Entry)`""
Or: 'Surname -like $entry'
(let the AD provider evaluate the variable, do not use embedded quoting)
Note: This approach fundamentally only works with stand-alone variable references, not with attempts to access properties (e.g or subexpressions (e.g. 'Surname -like $entry.Text'
)'Surname -like $(Get-EntryName)'
While the form { Surname -like $entry }
is often seen in practice, it is best avoided so as to prevent conceptual confusion - see this answer.
As for what you tried:
-Filter "Surname -like $entry"
Since you're using an expandable (double-quoted) string ("..."
), i.e. up-front string interpolation, the value of $entry
is placed as-is inside the resulting string value.
Thus, with $entry
containing verbatim rondon
, what the -Filter
argument receives is verbatim Surname -like rondon
, which causes a syntax error, because the RHS of the -like
operator must either be a quoted string or a reference to a PowerShell variable.
-Filter
parameter expects expression that are PowerShell-like, they are not PowerShell expressions, and instead interpreted by the Active Directory provider. The expression language supported in a -Filter
argument is both much more limited than what PowerShell supports and exhibits subtle yet important differences in behavior. Again, see this answer for background information.