Search code examples
powershellparameter-splatting

Splatting doesn't work with parameter -Filter


I have this long line I want to make easier to read:

$Mail = "[email protected]"    
Get-ADUser -Server example.com:3268 -Filter {EmailAddress -eq $Mail} -Properties CN,co,Company,Department,DisplayName,SamAccountName,State,Office,EmailAddress 

I read that it's nice to use splatting, so I'm trying:

$Params = @{
    Server = 'example.com:3268'
    Filter = '{ EmailAddress -eq $Mail }'
    Properties = 'CN,co,Company,Department,DisplayName,SamAccountName,State,Office,EmailAddress'
}

Get-ADUser @Params

But running this throws an error:

Get-ADUser : Error parsing query: '{ EmailAddress -eq [email protected] }' Error Message: 'syntax error' at position: '1'.
At line:1 char:1
+ Get-ADUser @Params
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

What am I missing?


Solution

  • You should pass a filter to the ActiveDirectory module cmdlets as a string. You're needlessly including brackets in your code:

    Get-ADUser -Filter "EmailAddress -eq '$Mail'"
    

    While you can pass a scriptblock, it's implicitly being turned into a string anyways. Additionally, you're passing your properties as a single string when it's expecting an array of string.


    The correct way:

    $aduserParams = @{
        Server     = 'example.com:3268'
        Filter     = "EmailAddress -eq '$Mail'"
        Properties = 'CN', 'co', 'Company', 'Department', 'DisplayName', 'SamAccountName', 'State', 'Office', 'EmailAddress'
    }
    Get-ADUser @aduserParams
    

    I suggest checking Get-Help for parameter types:

    Get-ADUser -Filter <string>
    [-ResultPageSize <int>]
    [-ResultSetSize <System.Nullable[System.Int32]>]
    [-SearchBase <string>]
    [-SearchScope {Base | OneLevel | Subtree}]
    [-AuthType {Negotiate | Basic}]
    [-Credential <PSCredential>]
    [-Partition <string>]
    [-Properties <string[]>]
    [-Server <string>]
    [<CommonParameters>]