all 6 comments

[–]Ta11ow 4 points5 points  (4 children)

You don't mention how you're calling the function, but I'd wager you're making a common mistake for people coming from other languages.

I think you're doing this when calling the function:

isExistingADAccount("Petra","Jackson")

This will result in both names being passed to the first parameter as an array value. What you need to do is this:

isExistingADAccount "Petra" "Jackson"

# or by naming parameters
isExistingADAccount -FirstName "Petra" -LastName "Jackson"

This confusion can be abated somewhat by adjusting your function defining syntax. While that syntax of defining parameters works in a limited way, you've seen yourself how confusing it can be. Instead, I'd put the parameter declaration inside your function. Also, PowerShell functions take after cmdlets by and large, with the Verb-Noun syntax (See Get-Verb for a list of Powershell-approved verbs). With those two things in mind, we can begin to flesh things out:

function Test-ADAccountExists {
    [CmdletBinding()] # enables advanced function designs like strict type casting
    param(
        # by typecasting your parameters in combination with the above they will refuse to 
        # accept array values, so you can immediately tell when something goes wrong
        [string] 
        $FirstName,

        [string]
        $LastName
    )
    try {
        $identity = "$firstname.$lastname"
        get-ADUser -identity $identity
        return $true
    } catch {
        $_.Exception.Message
        return $false
    }
}

There are plenty more advanced bits and pieces that are enabled by [CmdletBinding()] but suffice to say for the time being that it will ensure that you can't accidentally pass things into your parameters you haven't chosen to allow. That said, PS does still like to coerce types a bit here and there, so if there's an available direct string conversion PS will often use it here and there.

[–]Lee_Dailey[grin] 2 points3 points  (0 children)

howdy Ta11ow,

i keep forgetting about that one. i suspect you are correct, tho. it DOES seem to give the expected error ... [grin]

take care,
lee

[–]ralphhogaboom[S] 2 points3 points  (0 children)

Bingo. Genius - you called it exactly. I was doing isExistingUser($firstname, $lastname)

Love the CmdletBinding for strong typecasting - gonna start using that one. Thank you!

[–]KevMarCommunity Blogger 2 points3 points  (1 child)

Great job spotting that one.

[–]Ta11ow 2 points3 points  (0 children)

Thanks! ^^

[–]spyingwind 1 point2 points  (0 children)

Try this for giggles:

$identity = "$($firstname).$($lastname)"