1

I have two array's having more that 500,000 values and need to compare to find the difference. Some of the values in the array are $null. When I am trying to do the following code and I getting an error Compare-Object : Cannot bind argument to parameter 'ReferenceObject' because it is null

Is there any work around for this issue or is there a better and faster way to find the difference? I am only interested in the count of variance/difference.

Thanks!

Example Code:

$objSource = @('a', $null, 'c')
$objTarget = @('a', 'b','c')
Compare-Object -ReferenceObject $objSource -DifferenceObject $objTarget | Measure

Error Message:

Compare-Object : Cannot bind argument to parameter 'ReferenceObject' because it is null . At line:4 char:32
+ Compare-Object -ReferenceObject <<<<  $objSource -DifferenceObject $objTarget
    + CategoryInfo          : InvalidData: (:) [Compare-Object], ParameterBindingValid     ationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft     .PowerShell.Commands.CompareObjectCommand

2 Answers 2

3

The documentation states that this would happen if the -ReferenceObject or -DifferenceObject were $null but does not really cover if the any elements of those objects are.

NOTE: If the reference set or the difference set is null ($null), Compare-Object generates a terminating error.

Quick work around would be to replace those $null elements with a control character or something along those lines.

$objSource = @('a', $null, 'c') -replace "^$","null"
$objTarget = @('a', 'b','c') -replace "^$","null"
Compare-Object -ReferenceObject $objSource -DifferenceObject $objTarget

The -replace would remove those empty entries from the array with string "null". So we would have a visual indication of that data now. Unlikely that that text would be a natural element but you would have to be wary just the same. If null is not appropriate I would recommend bagel as a keyword!

Sign up to request clarification or add additional context in comments.

Comments

2

This seems to work:

$objSource = @('a', $null, 'c')
$objTarget = @('a', 'b','c')
Compare-Object -ReferenceObject ([string[]]$objSource) -DifferenceObject ([string[]]$objTarget) | Measure

1 Comment

Yes, this works but the result is always 2. I would like to find the variance count.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.