VMware Cloud Community
drwoodberry
Contributor
Contributor

Select Random Datastore

In the past I was able to create an array of datastores based on the prefix in the datastore name. From that array, I was able to randomly select which datastore to deploy a virtual machine too.

$datastoreArray = @()

    $myds = Get-datastore | where {$_.Name -contains "NFS"}

    foreach ($ds in $myds)

    {

    if (($ds.FreeSpaceMB) -gt ($ds.CapacityMB * .25))

      {

  $datastoreArray += $ds

    }

    }

  if ($datastoreArray.Count -eq 0)

  {

  Write-Host "There is not enough free space to create a Virtual Machine"

  exit

  }

  $dsNumber = ($rnd.next(0,$datastoreArray.count))

  $datastore = $datastoreArray[$dsNumber]

    return $datastore

Is there a better way to do this? I would prefer to balance the deployments. Also this does not appear to be working any longer,

0 Kudos
2 Replies
RvdNieuwendijk
Leadership
Leadership

If you have a vSphere Enterprise Plus license I would use Datastore Clusters and I would deploy a VM to a Datastore Cluster. The Datastore Cluster will select the optimal datastore based on capacity and I/O load.

Otherwise you can use the following PowerCLI script to select a random datastore:

Get-datastore |

Where-Object {$_.Name -like "*NFS*" -and $_.FreeSpaceMB -gt ($_.CapacityMB * 0.25)} |

Get-Random -Count 1

If you want to select the datastore that has the most free space then you can use:

Get-datastore |

Where-Object {$_.Name -like "*NFS*" -and $_.FreeSpaceMB -gt ($_.CapacityMB * 0.25)} |

Sort-Object -Property FreeSpaceMB -Descending |

Select-Object -First 1

Message was edited by: Robert van den Nieuwendijk Added the second example.

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
drwoodberry
Contributor
Contributor

Thanks...because of the deployment I can not use Datastore clusters...I wish I could though.

0 Kudos