[UPDATED] Figuring Out Pipeline Input Binding Using Trace-Command

Look under the hood to see what PowerShell is doing when piping data from one command to another

Don Jones

December 6, 2011

2 Min Read
ITPro Today logo

Update: I've posted a detailed walk-through example, including screen shots, at PowerShell.com. It shows not only how to run Trace-Command, but how to interpret its parameter binding output.

 

Sometimes, stringing PowerShell commands together in a pipeline can be difficult. The trick is in one simple concept: When you pipe data from one command to the next, the data has to be "attached," or "bound," to a parameter of the second command. For example:

Get-ADUser -filter * | Set-ADUser -City 'Las Vegas'

The first command is producing a certain kind of object, and placing those objects into the pipeline. The second command has to "pick up" those objects from the pipeline, and attach, or bind, those objects to one of its own parameters.

Which parameter will it choose?

It depends. There are two ways that data can be bound to a parameter. The first method, which PowerShell prefers, is called ByValue. It means that the second command must have a parameter which (a) accepts the exact type of object produced by the first command, and (b) that parameter must be able to accept pipeline input ByValue. Reading the -full help for a cmdlet will usually tell you if both (a) and (b) are true.

A neat trick is to get PowerShell to actually tell you what it's doing.

Trace-Command -Name ParameterBinding -PSHost -Expression { Get-ADUser -filter * | Set-ADUser -City 'Las Vegas' -whatif }

Just drop your entire pipeline command into the -Expression parameter's {script block}. Note that I added a -whatif, since I'm just testing this and don't want it to actually do the work. The output is somewhat complex, but you'll clearly see PowerShell attempting to do the ByValue parameter binding, and you'll see which parameter of Set-ADUser received the pipeline input. If it wasn't the parameter you expected… well, then you can change your command. Just seeing what was going on can be tremendously helpful!

Want to ask a question about this article? I'll answer at http://powershell.com/cs/forums/230.aspx!



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like