PowerShell function ValueFromPipelineByPropertyName not using alias parameter name

Question:

Trying to create a function that takes objects on the pipeline using the alias property. I’m not sure where this is going wrong.

Example of the process:

If I run this command:

the output looks like this:

The Function never seems to grab the sn and givenname attributes from the passed in object. What am I missing?

Answer:

The AD Cmdlets are to blame here

The problem here is that the AD Cmdlets return objects in really non-standard ways. For instance, with any other cmdlet if you take the output of the command and select a non-existing property, you’ll get back nothing, like this:

See, nothing. Sure, it says Hamster, but there is no actual Object there. This is standard PowerShell behavior.

Now, look at what Get-ADUser does instead:

It creates a $null! So what will happen with your function is that PowerShell will look for a property of -LastName or -FirstName, get a $null and then stop right there. It sucks!

The best way around this is to swap the parameter names like this, and it will still work:

Want to know more?

Check out this awesome answer from /u/JBSmith on the topic.

Source:

PowerShell function ValueFromPipelineByPropertyName not using alias parameter name by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply