|
|
PowerShell Compare-ObjectCompare-Object to Find the Differences Between FilesScenario: I had a folder of files. Many of those files were missing a phrase, I wanted a list of files with these deficiencies. Stage 1 was to create a text file containing a directory listing. Stage 2 was to create another file listing only those files containing a particular phrase. Stage 3 was to employ Compare-Object, process the two files, and then create a third file with a list of all the files that were missing my particular phrase. Topics for PowerShell Compare-Object Cmdlet
♣ Mission to Generate a List of DifferencesIn this mission I had a directory of files. Some of those files were missing a phrase, I wanted a list of files with these deficiencies. Stage one was to create a text file containing a directory listing. Stage two was to create another file listing only those files containing a particular phrase. Stage three was to launch Windows PowerShell and then call for Compare-Object. Using this technique you can process the two files and create a third file with a list of all the files that were missing my particular phrase. In these ezine I just want to focus on stage three, generating a list of differences. Preparation: Use PowerShell's Built-In HelpThis script is a useful reminder to see Compare-Object's parameters. # Example of PowerShell Compare-Object Note 1: With the Compare-Object cmdlet, there are two required parameters -referenceObject and -differenceObject. For most examples -referenceObject controls the master content, the file which holds ALL the information, while -differenceObject has the secondary or 'after the event' file. Also note what help says about these parameters, what we learn is that that the position of these parameters is important, reference list first, difference list second. Note 2: In a production script we employ Get-Content to open the file, read the text and assign the content to a variable. For example $strReference = Get-Content "c:\scripts\list.txt" Note 3: Please investigate more parameters such as -IncludeEqual and -syncWindow. Incidentally, there is a PowerShell diff alias. Example 1: To Compare Two Files, and List Their DifferencesFor the sake of clarity, and so that we focus on Compare-Object, I have scaled down our mission to tackle only comparing two files. The best way to understand this example is if you pretend that you have a shopping list. Preparation ShopList: Save these 10 items into a text file, I called mine C:\temp\ShopList.txt ® |