Powershell: Troubleshoot the pipeline

I found this excellent tip courtesy of Don Jones which I’m going to coffee \ pasta here for future reference.  This is definitely my cmdlet of the year:

This month, I want to take a look at one of my favorite troubleshooting cmdlets. Take this, for example:

Get-WMIObject Win32_Service | Where { $_.State -ne "Running"
-and $_.StartMode -eq "Automatic" } | ForEach-Object { $_.Start() }

On the surface, this would seem to start all services that are set to start automatically but have not yet started for some reason. This doesn’t actually work, though, and finding out why it doesn’t work can be tricky since you can’t peer inside the middle of the pipeline. That is, you can’t peer inside the pipeline unless you use Tee-Object.

Tee-Object redirects objects to a file (or into a variable) and passes them down the pipeline. For example:

Get-WMIObject Win32_Service | Tee-Object AllServices.csv | Where 
{ $_.State -ne "Running" -and $_.StartMode -eq "Automatic" } | 
Tee-Object FilteredServices.csv | ForEach-Object { $_.Start() }

This modification lets me see what happens after each pipeline command, and I quickly discover that my FilteredServices.csv file contains nothing! No wonder this script didn’t work! A bit more research reveals the root cause of the problem—StartMode is “Auto” not “Automatic”—and Tee-Object let me pinpoint exactly where the problem was occurring.

Be the first to comment

Leave a Reply