Prof. Powershell

Comparison and Contrast

Which of these things is not like the other? Use the Compare-Object cmdlet to find out.

There may be times when need to compare objects to see what is different. This if often the case when you want to capture state information and see what has changed between "snapshots." For example, you might want to troubleshoot a problem by capturing process information in the middle of the night and compare it to a known good state. Let me show you how to use the Compare-Object cmdlet, which has an alias of Diff.

First capture the current running processes:

PS C:\> $before=get-process

Then start Notepad and Calculator. Now grab an after snapshot:

PS C:\> $after=get-process

The Compare-Object cmdlet compares a source object to a reference object. In our example we want to compare before and after:

PS C:\> diff $before $after

What you'll likely see is a long list with a side indicator that tells you which item doesn't belong in the other. Remember we're dealing with a collection of process objects and even though a process like PowerShell is still running, some properties like memory utilization will have changed between snapshots. That's normal. What we want is to narrow the comparison. We can do that by selecting a property:

PS C:\> diff $before $after -property Name

Now you should see that the Notepad and Calculator properties are only found in $after. Here's one more quick example. Get all the current running services:

PS C:\> $now=get-service

Stop or start some services and take another snapshot:

PS C>\> $later=get-service

You can use Compare-Object to return more than one property:

PS C:\> diff $now $later -property Status,Name

This will show the differences based on status as well as showing the service name.

Remember, you can use the Export cmdlets to save state information and then re-create the objects using the corresponding Import cmdlet. Save a current snapshot to a variable and compare the two.

Note that this is just an intro; be sure to look at the help file for Compare-Object to find out more.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular