Wednesday

powershell compare two csv files and output differences

 I had to compare data returned from two APIs - one JSON another XML so

1. I used this  viewer to convert json to csv and this app to save xml to csv

2. I used this PowerShell to show difference between two csv files:


Start-Transcript -Path result-10.csv


$mas = Import-Csv 1.csv
$marko = Import-Csv 2.csv

$md=@{}
#converting one csv into hashmap for quicker search
foreach($r in $mas){
    foreach($a in $r.psobject.properties){
        $fn=$a.name
        $val=$a.value
        $md.Add($fn.ToLower(),$val)
    }
}

echo "fieldName,csv1,csv2"

    foreach($r in $marko){
        foreach($a in $r.psobject.properties){

            $k=$a.name.replace("_","").toLower()
            if ($md.ContainsKey($k)){
                if ($md[$k] -ne $a.value){
                  echo "$($a.name),$($a.value),$($md[$k])"
                }
            }
        }
    }
Stop-Transcript

No comments:

test smtp server with powershell

Send-MailMessage -SMTPServer smtp.domain.com -To [email protected] -From [email protected] -Subject "This is a test email" -Body ...