Compare Objects In Single PowerShell Array

Viewed 315

I've searched but I can only find posts comparing two different arrays in PowerShell. What I'm trying to do is compare the contents within a single array to see if everything inside is equal (e.g.; 2,2,2,2 = true; 2,2,2,3 = false). Does anyone have any ideas how this might be accomplished? Thanks.

3 Answers

You can make use of Get-Unique

$array = @(2, 2, 2, 2)

if (($array | Get-Unique).Count -gt 1) {
    Write-Host "some odd ones"
} else {
    Write-Host "all the same"
}

It will count how many unique items exist in the array

We pass that result to be evaluated by the if statement

If there is more than one unique result from Get-Unique, we know that all elements are not equal

Check the SS64 page

You can try something like this which iterates through element and compares it to the last to make sure that they are all equal.

You could make a function out of this logic that takes an array as a parameter and returns either $true or $false so that you can reuse. You may also be able to improve upon it by breaking out of the loop if you find something that is not equal.

$arr = (2,2,2,3)

$notEqual = $false;

for ($i = 1; $i -lt $arr.Length; $i++)
{
  if ($arr[$i] -ne $arr[$i-1]) {$notEqual = $true}
}

if ($notEqual)
{
    Write-Host "Array elements not equal"
}
else
{
    Write-Host "Array members are qual"
}

Another way could be to make a hashtable. Group-Object can do the work for you. If there ends up being more than one entry then they aren't all equal. You could then look at all the unique values by pulling the hash table keys.

$array = 2,2,2,2,3,2,3,2

$grouped = $array | Group-Object -AsHashTable

if($grouped.count -gt 1){
    Write-Host All array elements are not equal -ForegroundColor Yellow

    Write-Host Unique values $grouped.keys
}
else {
    Write-Host All array elements are equal -ForegroundColor Green
}

enter image description here

$array = 2,2,2,2,2,2

$grouped = $array | Group-Object -AsHashTable

if($grouped.count -gt 1){
    Write-Host All array elements are not equal -ForegroundColor Yellow

    Write-Host Unique values $grouped.keys
}
else {
    Write-Host All array elements are equal -ForegroundColor Green
}

enter image description here

Related