Thursday, February 6, 2014

What i found while playing with Group-Object Command

I am big fan of Group-Object command. If anybody asks you how many types of files are there in particular directory, hey it is one liner.

 Get-ChildItem | Group-Object Extension


Somebody asks you how many services are running and how many are stopped, now suppose Group-Object is not there, below is the path you will probably (there are many more other ways) you will take, in which first you will try to find running processes then stopped, then probably pipe that to Measure-Object to find the count of each type of Service.





















If you now Group-Object you can achieve that in one liner.




This is great, there are much more parameters that can be used with Group-Object.

For that just type
PS> Help Group-Object -Full

So, if you have just read the help of Group-Obejct, which I intended, you would know that Group-Object can do
1. Group Object based on a particular property
2. And output can be an hashtable if you use parameter -Ashashtable.

If I ask you get me all services which CanPauseAndContinue, below is the command.








 
If for some reason, you want result to be hashtable, use -asHashtable parameter as below.





I may save the same input in a variable called Services.

PS > $Services= Get-Service | Group-Object Status -AsHashTable

Now $Services.Stopped should give me all Services those are stopped, right?

No, It gave me null.   :-(









But why it is happening, Is it a bug?  answer again is No.

So I pinged my friend Dexter whose blog you can read at http://dexterposh.blogspot.in/.

He told me to use -AsString parameter and it worked, I got all Stopped services when I used $services.Stopped.



















But question arises Why?
Then I did  run below command.




Status has type System.ServiceProcess.ServiceController, but when I use $service.Running, powershell treat Running as String. String Running is not equal to System.ServiceProcess.ServiceController Running, both are different.

So what -Asstring parameter did was change hashtable keys to strings. So now both Running are string and I got my required output.

Let me know for any question.

Happy Scripting!!!!