PowerShell: Looking behind the Scenes (Trace-Command)

What happens when you run a PowerShell Command? How does it work? There is a small but very informational Cmdlet, which helps you to look behind the scenes. The command is called Trace-Command. While running Trace-Command you will have the opportunity to learn a lot about the PowerShell mechanics.

Discovering Parameter Binding

I want to see what happens when using Get-ChildItem by omitting the path parameter. Note that Get-ChildItem -Path C:\Temp and Get-ChildItem C:\Temp do the same. So I run Trace-Command without the path parameter.

Trace-Command -Name CommandDiscovery,ParameterBinding -Expression {Get-ChildItem C:\Temp} -PSHost


It’s interesting to see that the parameter binding takes place automatically. C:\Temp is bounded to the Path parameter. Why? The Path parameter is a positional parameter and it’s position is 0. That means, the first argument (C:\Temp) will be bounded to the path parameter. Look at this:

Get-Help Get-Childitem -Parameter Path


Discovering the Pipeline

The next example shows the work of the Pipeline. I run Trace-Command with Foreach-Object and New-Item. This creates the file File1.txt. I only provide the File Name without the number. The number (1) is taken from the pipe.

Trace-Command -Name ParameterBinding -Expression {1 | Foreach-Object {New-Item -Path C:\Temp -Name File$_.txt}} -PSHost


Further thoughts

To find out more about tracing run Get-TraceSource.

Get-TraceSource | Format-Table -AutoSize


Categories: PowerShell

Tagged as: ,

1 reply »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s