简体   繁体   中英

Powershell Multiple values comparison

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?

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM