I'm using Powershell to compare two, large csv files and output the rows which don't match. Once the two output files are made (one for the differences on each), I bring them up on Excel. Now I want to highlight the mismatching fields for the output to be easily read by my customer. Starting where I open the files in Excel, my current code is:

$excel= New-Object -ComObject "excel.application"
for($i=2; $i -le $row; $i++)
{if($comp1.cells.item($i,1).value2 -eq 'pntval'){if($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=1'){$comp1.cells.item($i,4).interior.colorindex=3} elseif($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=2'){$comp1.cells.item($i,6).interior.colorindex=3} elseif($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=3'){$comp1.cells.item($i,5).interior.colorindex=3} elseif($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=4'){$comp1.cells.item($i,7).interior.colorindex=3}}}

for($i=2; $i -le $row; $i++)
{if($comp2.cells.item($i,1).value2 -eq 'pntval'){if($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=1'){$comp2.cells.item($i,4).interior.colorindex=3} elseif($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=2'){$comp2.cells.item($i,6).interior.colorindex=3} elseif($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=3'){$comp2.cells.item($i,5).interior.colorindex=3} elseif($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=4'){$comp2.cells.item($i,7).interior.colorindex=3}}}

This code works, but the part which highlights the fields (the for loops on bottom) is cripplingly slow. How can I speed this up?


1 Answer 1


While this isn't a direct way to speed up PowerShell interaction with Excel, I suspect most people having this problem will find this helpful. I ended up writing a VBA macro ("Sides") that opens in a third workbook, along with the two of interest. I then call it from Powershell. All together, I came up with:

$excel= New-Object -ComObject "excel.application"

This runs really smoothly and does exactly what I want. Granted, you have to know a little VBA, but that wasn't a problem for me.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.