Author Posts

January 21, 2016 at 4:33 pm

Probably something obvious like a time stamp or something but I noticed a very simple operation failing:

$csvfile = import-csv C:\somefile.csv
$csvfile2 = import-csv C:\somefile.csv
IF ($csvfile -ne -$csvfile2) {write-host "file has changed"}

Again, I'm guessing there's some hidden value saying the import time or some such but basically I don't expect a write host to happen because I'm literally just importing the real file twice and comparing the variables so they should be identical.

Yes I can think of tons of other ways to do this but as a academically: why aren't these two arrays equal in the eyes of a IF statement?

January 21, 2016 at 4:39 pm

Well, let's be clear – the If statement doesn't care one way or another. It's the comparison operator you've used, -ne. It simply isn't designed to compare collections of objects, which is what you've given it. So this isn't a hidden value or anything; you've simply gone beyond the capabilities of the comparison operator.

Instead, I'd do something like:

diff $csvfile $csvfile2 | measure

The resulting object will tell you how many differences there are. Have your If statement see if it's zero or not. Compare-Object (the diff alias) is designed to compare sets of objects.

Now, another approach would be to turn these into strings.

$csv = import-csv whatever.csv | out-string
$csv2 = import-csv whatever2.csv | out-string

Now you could probably compare them using -ne or -eq, because they're just simple strings, albeit potentially large (and memory-consuming) ones.

It'd actually be much more memory- and processor- efficient to generate a checksum from each file, and compare the checksums.

January 21, 2016 at 4:46 pm

Thank you for this answer.

I'm not actually using the variable in this way in my script, it was just a simple example that confused me. It makes sense that I'm "breaking" -ne switch.

For better context the actual function imports the array, reads and possibly modifies the loaded variable as it gets updated information .... then eventually writes the changes back to file on exit but I was simply trying to find a way to "check" if anything actually changed before wasting disk cycles. So what started as a simple "lets store the array in two variables and compare at the end the control and change" turned into "OK nothing should have changed, why did it try to overwrite"?

Your explanation is perfect, I"m using the wrong tool for the job.