Home > Back-end >  Powershell Multiple values comparison
Powershell Multiple values comparison

Time:04-02

I obtain the available raw disks on my VM by using

$availDisks = Get-PhysicalDisk -CanPool $true

The $availDisks contains 3 RAW disks I would like to effectively compare the size of the disks, and if they are the same size, to stripe them.

$availDisks.Size gives me the output of the 3 disks, but I need to compare each one of them.

The method I used is

$size = $availDisks[0].size
foreach($disk in $availDisks){
   if($disk.size -eq $size){
      Write-Host "The disk is equal to the desired size"
      continue with the disk striping
   }else{
      Write-Error "One of the disks is not matching the size"
      Do something else
   }
}

Is there a more effective method?

CodePudding user response:

You can use Group-Object targeting the Size property of the object:

Get-PhysicalDisk -CanPool $true | Group-Object Size |
    Where-Object Count -GT 1 | ForEach-Object Group

Group the objects by the value of the Size property, filter the groups where the Count is greater than 1 (meaning disks with the same Size), then output each filtered object. If you don't get any output from this, means that the disks have different sizes.

CodePudding user response:

Use Select-Object -Unique on the disk sizes to check if there is exactly one unique value. If there is any other value you either have no disks or a non-equal sizing of disks.

if( @( $availDisks.Size | Select-Object -Unique ).Count -ne 1) {
  Write-Error "One of the disks is not matching the size"
  # Do something else
} else {
  Write-Host "The disks are equal to the desired sizing"
  # Continue with the disk striping
}
  • Related