Author Posts

November 3, 2015 at 11:30 am

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

November 3, 2015 at 11:43 am

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*" }

November 3, 2015 at 1:26 pm

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 }.

November 3, 2015 at 1:55 pm

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?

November 3, 2015 at 1:58 pm

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

November 3, 2015 at 3:09 pm

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*" }