How can I use the Active Directory Filter in an Advanced Function?

This topic contains 5 replies, has 3 voices, and was last updated by  Chris Wolfenden 1 year, 11 months ago.

  • Author
    Posts
  • #31630

    Chris Salzgeber
    Participant

    I'm writing a function which contains a [String]Filter parameter. I'd like the value of the parameter to be declared the same way the filter is declared in Get-ADUser -Filter. Wrapping the parameter value in double quotation marks won't work, as it interferes with the double quotation marks present in the filter. What do I need to do so that the following code will work?

    . .\MyAdvancedFunction.ps1
    MyAdvancedFunction -Filter { Name -Like "Test" }
    $Filter
    { Name -Like "Test" }
    Get-ADUser -Filter $Filter

  • #31632

    Chris Wolfenden
    Participant

    Are you receiving an error? It appears to work as intended (as long as you fix your filter). Here was the test I used

    function test-function {
    
        [CmdletBinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [String]$Filter
        )
    
        Get-ADUser -Filter $Filter
    }
    
    test-function -Filter { Name -like "test*" }
    
  • #31634

    Dave Wyatt
    Moderator

    PowerShell will happily convert a ScriptBlock object to a String for you. That's what happens when you call the AD cmdlets and use the syntax of -Filter { Something }.

  • #31636

    Chris Salzgeber
    Participant

    PS C:\Users\Chris> function test-function {

    [CmdletBinding()]
    Param (
    [Parameter(Mandatory=$false)]
    [String]$Filter
    )

    Get-ADUser -Filter $Filter
    }

    test-function -Filter { Name -like "test*" }

    PS C:\Users\Chris> function test-function {

    [CmdletBinding()]
    Param (
    [Parameter(Mandatory=$false)]
    [String]$Filter
    )

    }

    PS C:\Users\Chris> test-function -filter { name -like * }

    PS C:\Users\Chris> $filter

    PS C:\Users\Chris>

    Doesn't look like $Filter contains that ScriptBlock. Ideas?

  • #31637

    Dave Wyatt
    Moderator

    $Filter only exists as a variable inside the function. You can't check it from the calling scope like that.

  • #31640

    Chris Wolfenden
    Participant

    As Dave mentioned the variable only exists within the function. If you want to verify the contents of the $Filter variable while you are developing you can add it into the function. Alternatively, you can use the debug functionality in ISE to check it.

    function test-function {
    
        [CmdletBinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [String]$Filter
        )
    	"This is the contents of the Filter variable: $Filter"
        Get-ADUser -Filter $Filter
    }
    
    test-function -Filter { Name -like "test*" }
    

You must be logged in to reply to this topic.