Categories
PowerShell

compare two lists with PowerShell

I am asked occasionally to compare a list of employee ID numbers to find the differences or the matches. Notepad++ does not do a great job of this, so I put together a quick PowerShell solution.

$dupes = @()
[System.Collections.ArrayList]$arrA = Get-Content U:\listA.txt
[System.Collections.ArrayList]$arrB = Get-Content U:\listB.txt
foreach ($itemA in $arrA) {
if ($arrB -match $itemA) {
$arrB.Remove($itemA)
$dupes += $itemA
}
}

Now $arrB contains only items from listB.txt that do not also appear on listA.txt. Also $dupes contains the items that exist in both files.

By Tommy Doan

BF-ITS(Systems)

One reply on “compare two lists with PowerShell”

I’ve found that sometimes the files I need to compare are quite large and may take a few minutes to process using this method. So I found a simple way to add a progress indicator bar to the script, which helps me know the script is actually still working rather than just stuck in an endless loop.

$dupes = @()
[System.Collections.ArrayList]$arrBefore = Get-Content U:\before.txt
[System.Collections.ArrayList]$arrAfter = Get-Content U:\after.txt

$i = 0
foreach ($itemBefore in $arrBefore) {
$i++
Write-Progress -Activity "Comparing lines in the two files..." `
-PercentComplete (($i / $arrBefore.count)*100) -CurrentOperation $itemBefore
if ($arrAfter -match $itemBefore) {
$arrAfter.Remove($itemBefore)
$dupes += $itemBefore
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *