RowdyVinson
RowdyVinson

Reputation: 150

Comparing arrays where one is potentially null

I have two variables that, when populated, are arrays, but the process that populated them will occasionally not return anything and leave one/both of them null. The issue I'm running in to is that I run Compare-Object against them to find missing objects. If one of the arrays is null, compare-object fails with error:

Compare-Object : Cannot bind argument to parameter 'ReferenceObject' because it is null.

I'm working around this for now with a couple of if statements and a try/catch, but I'd like to know if there is a simpler way to do this. How do i compare 2 arrays and find differences if one of them can occasionally be null?

Upvotes: 0

Views: 133

Answers (1)

Alex
Alex

Reputation: 802

Using the try/catch approach is likely going to be your only option on this one. The help reads:

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

You could create a catch that catches the null error and then outputs the array that isn't null to show all of the values from the null array that are missing.

Upvotes: 1

Related Questions