Putting Square Pegs in Square Holes with PowerShell 2.0

So you’ve got a Service object in your hands — maybe you ran something like Get-Service “Print Spooler”. 

So now what? Well, one logical thing to do might be to restart that service (perhaps to fix a stuck print queue).

There’s a cmdlet for that, called Restart-Service. The principle of pipelining says that I should be able to just feed the Print Spooler service object to the Restart-Service cmdlet.

It turns out that works. I can simply do this:

Note the use of the –force; this service has dependent services, so PowerShell wants to know that you are REALLY sure of what you are doing.

So how did that work? How did Restart-Service know what to do with the incoming Print Spooler service? It helps to take a close look at the help file for Restart-Service.  Have a look:

Take a close look at the data type named for the –InputObject parameter of Restart-Service. It’s looking for objects of the “ServiceController” type. That should ring a bell for you — that’s the same type of object that I get from my call to Get-Service. So far, so good, but how does PowerShell know to associate an incoming ServiceController object with the –InputObject parameter? Take another look at the help file (using the –full switch) for Restart-Service:

Note that the –InputObject parameter is designed to accept pipeline input — it WANTS to find data on the pipeline that it can work with. Specifically, –InputObject accepts pipeline input “ByValue” or, in other words, it consumes the entire incoming object whole. This is the mechanism by which PowerShell feeds the incoming service from the call to Get-Service (Print Spooler in my example) as an input to Restart-Service.

In this article

Join the Conversation