Get-ADUser -Filter fails when comparing to an object's property

14,267

Alright, I had a discussion with some of my fellow PowerShell MVPs, and the answer as to why is really quite interesting.

For the quick answer, this is how you do get the AD User while preserving the structure of your code:

Get-ADUser -Filter "Emailaddress -eq '$($line.email)'"

You can quickly test to see what is happening by just running the quoted code on its own:

"Emailaddress -eq '$($line.email)'"
>Emailaddress -eq '[email protected]'

As to why, well, the outside set of quotes always wins in PowerShell, and the *-ADUser -Filter Cmdlets expect the value to be provided in single quotes.

According to Dave Wyatt, PowerShell MVP and all around cool guy and Mike Robbins, also MVP and well-respected around the community, the way that the ADUser Cmdlets expand variables is somewhat unstandard when compared to the rest of PowerShell's code base. They described the action of Variable expansion as 'strange voodoo', which seems about right.

If you'd like to learn a little bit more, follow up on Mike's awesomely detailed blog post on just this type of scenario PowerShell: When Best Practices and Accurate Results Collide

Share:
14,267
mart2001
Author by

mart2001

Updated on August 04, 2022

Comments

  • mart2001
    mart2001 almost 2 years

    I have a powershell question that has to do with importing a csv file, then going through a foreach through the csv file.

    I have something like the following:

    $infile = "c:\temp\infile.csv"
    $outfile = "c:\temp\outfile.csv"
    
    $csv = Import-csv -path $infile
    foreach ($line in $csv)
    {
      $data = Get-ADUser -Filter {EmailAddress -eq $line.email} -Property Mail |     Select-Object -ExpandProperty SamAccountName
    }
    

    When I do something like that, I get the following error:

    Get-ADUser : Property: 'email' not found in object of type: 'System.Management.Automation.PSCustomObject'.
    At C:\Temp\program1.ps1:11 char:24
    +         $ad_data = Get-ADUser <<<<  -Filter {EmailAddress -eq $line.email} -Property Mail | Select-Object -ExpandProperty SamAccountName
        + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
        + FullyQualifiedErrorId : Property: 'email' not found in object of type: 'System.Management.Automation.PSCustomObject'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
    

    But if I do something like:

        $var = $line.email
        $data = Get-ADUser -Filter {EmailAddress -eq $var} -Property Mail | Select-Object -ExpandProperty SamAccountName
    

    Why does the second method works but the first method throws an error?

    Thanks,