Search code examples
powershellcompareobject

How to get compare-object output in file along with record count


I am trying to append the output of compare-object of 2 rhash files to a file as well as count the records. The out-file was previously created in the script to capture a start time and eventually an end and elapsed time. This is my code for the compare and counter:

Compare-Object @objects | 
    % {$differences+=1} | 
        out-file -FilePath $resultsDir\CFRunResults-$runTimeStamp.txt -append

This produces the file but it is empty except for the start time written to it previously, and the $differences variable updates correctly but it doesn't appear in the file either. How would I go about getting the default compare-object output in a file as well as append to the output file the count of number of differences? Actually to be precise, in my application there will always be 2 differences I don't care about and since the remaining differences would be hash values for the same file list, differences on one side of the compare will have an equal number on the other. I plan to compute the value written to output file as $differences = ($differences - 2)/2.


Solution

  • Building on the helpful comments:

    • The simplest and faster solution is:

      @(Compare-Object @objects).Count > $resultsDir\CFRunResults-$runTimeStamp.txt
      
      • Use @(...), the array-subexpression operator to capture the output from Compare-Object and make sure it is treated as an array even if there happens to be just one output object.

      • Use .Count to get the array's element count (.Length would work too, but .Count is preferable as it works on other list-like types too).

      • Redirection operator > is in effect the same as Out-File with its default behavior. Thus, if no opt-in behavior such as -Encoding is needed, it is a more concise alternative. Note that unless you meant to append to preexisting content in the output file, there's no need for -Append (whose equivalent redirection operator is >>).

    • The immediate problem with your code was:

      • $differences+=1 is an assignment and assignments do not produce pipeline output, so that Out-File received no input.

      • However, by enclosing assignments in (...), the grouping operator, you can make assignments pass the assigned value through.

        • As an aside: the simpler equivalent of $differences+=1 is ++$differences, i.e. use of the prefix form of the increment operator.

        • A simplified example:

          # -> !! NO OUTPUT
          $num = 0
          'a', 'b', 'c' | % { $num+=1 }
          
          # -> Outputs 1, 2, 3 - thanks to the (...) enclosure
          $num = 0
          'a', 'b', 'c' | % { ($num+=1) }