4 ms·
I started off as a PowerShell fan, but my introductory experience has been pretty poor. A little while back, I tried testing the output of a sorting algorithm w
by slavik81 11y ago
I started off as a PowerShell fan, but my introductory experience has been pretty poor. A little while back, I tried testing the output of a sorting algorithm with PowerShell. I wrote a line of bash to check my results:
diff <(cat output.txt) <(cat output.txt | sort -n)
Then I wrote the PowerShell:
get-content output.txt | foreach-object { [Int] $_ } | sort-object | out-file -encoding ascii sorted.txt
compare-object (get-content output.txt) (get-content sorted.txt)
Yeah, it's a lot longer. It was the bug that really soured me, though. The files compare as identical even if output.txt is not sorted.
You go read Microsoft tutorials [1] and they tell you to use Get-Content (cat) and Compare-Object (diff) like this for comparing files, but what they don't tell you is that order is ignored. Given how often I see the above code cited online for comparing files [2][3], I'm not sure that many people actually understand this.
I still haven't actually figured out how you properly compare files with PowerShell. I call fc.exe now, but its output is pretty gnarly so all I use is the return value.
[1] https://technet.microsoft.com/en-us/library/Ee156812.aspx https://technet.microsoft.com/en-us/library/Ee156812.aspx
[2] http://blogs.technet.com/b/heyscriptingguy/archive/2015/04/01/use-powershell-to-compare-two-files.aspx http://blogs.technet.com/b/heyscriptingguy/archive/2015/04/0...
[3] http://serverfault.com/questions/5598/how-do-i-diff-two-text-files-in-windows-powershell http://serverfault.com/questions/5598/how-do-i-diff-two-text...
- bjourne 11y agoAFAICT, you are just trying to check if a file is sorted? Then wouldn't: diff (cat out.txt | sort | out-string) (cat out.txt -raw) do it?
- slavik81 11y agoYeah, actually. Though, I'd still include the cast to int, because I need to sort numerically, not lexicographically. I suppose the lesson is that if you want to preserve line order, you need to use -raw to prevent Get-Content (cat) from splitting the file into multiple lines. That still ruins the output text from Compare-Object (diff), but it's cleaner than fc.exe. Thanks.