How do I compare two arrays of DataRow objects in PowerShell?

Question!

I have two arrays of System.Data.DataRow objects which I want to compare.

The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted.

How do I do this in PowerShell?



Answers

Do you need two arrays of DataRows? the DataRow object has a RowState property which will give you what you require. See the MSDN Docs: http://msdn.microsoft.com/



I wrote a script to do this a little while back. The script (Compare-QueryResults.ps1) is available here and you will also need my Run-SQLQuery script (available here) or you can replace that with a script or function of your own.

Basically, what the script does is take the results of each of your queries and break the datarows apart so that each field is its own object. It then uses Compare-Object to check for any differences between the data in those rows. It returns a comparison object that shows you all the differences between the data returned.

The results are an object, so you can save them to a variable and use Sort-Object or the Format-* cmdlets with them.

Good luck. If you have any problems with the scripts, let me know, I'd be happy to walk you through them. I've been using them for application testing, seeing what rows are being modified by different actions in a program.



Obviously this is one of those questions where the only real answer is "it depends."

The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.

The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.

The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:

try { 
    something(); 
} catch (Exception ex) {}

or this in Python:

try:
    something()
except:
    pass

Because these can be some of the hardest issues to track down.

A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.

By : John


This video can help you solving your question :)
By: admin