11

Is there a way for the Compare-Object cmdlet to anticipate on $Null values?

For example when I'm trying to compare 2 values like this:

Compare-Object -ReferenceObject $Value1 -DifferenceObject $Value2 

I commonly get the following error:

Cannot bind argument to parameter 'ReferenceObject' because it is null

My question is: Is there a way to say: if either one of them equals $null ; do something

1

5 Answers 5

24

This accepts null values:

Compare-Object -ReferenceObject @($Value1 | Select-Object) -DifferenceObject @($Value2 | Select-Object)
Sign up to request clarification or add additional context in comments.

4 Comments

This works marvelously for what I was looking for. I'm importing from AD, but if the array is null, I error. I want to get the result that object is different from object2 (null) if that is the case. This does it in a simple manor without having to write evaluation cases for objects.
I noticed the pipe to Select-Object wasn't necessary in my tests. Can you explain why you used it in your answer?
@($null).Count 1 @($null | Select-Object).Count 0
Thanks for this answer. Could you explain why this works? Is it because Select-Object always returns an object whereas e.g. get-content returns a string of bytes?
5

Help on Compare-object says:

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

So your only options would seem to be a trap or try/catch.

Comments

1
 if($Value1 -eq $NULL){
     return
 }
 Compare-Object -ReferenceObject $Value1 -DifferenceObject $Value2 

2 Comments

This would be a stronger answer if you explain it.
It's just an alternative to try/catch. If the first value is NULL stop. If isn't NULL, you can Compare the Object. I don't know PS good enough to get those try/catch phrases working.
1

This does something if null:

if ($Value1 -ne $null -and $Value2 -ne $null) {
    Compare-Object -ReferenceObject $Value1 -DifferenceObject $Value2
}
else {
    #do something
}

Comments

1

There is a workaround you can use

First, create two empty array object

$reference = @()
$difference = @() 

Now

Check your sources array if not null and add them to previously créated array

If( $array1 -ne $null ){ $reference.addrange($array1) 
If($array2 -ne $null) { $diffrence.addrange($array2) 

Now you are sure that your reference array and diffirence array are not null even they could be empty, and you can securely do comparaison

Compare-object -referenceObject $reference -differenceObject $difference 

Comments

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.