When deploying some virtual machines in a test environment I ran into the following problem. In most cases, I make use of a VMware vCenter Storage DRS cluster, in this case when deploying a virtual machine the best-suited datastore is selected for the virtual machines. The only problem is not all customers are entitled to use Storage DRS, because Storage DRS requires a vSphere Enterprise Plus license.
So I needed to create a workaround to select a datastore with enough space. The default PowerCLI behavior is selecting the first datastore detected on a alphabetic order.
So when you are deploying let’s say twenty virtual machines all those virtual machines will be put on the first datastore, so that isn’t going to work well in most cases.
PowerCLI Code
To solve the problem I created the following PowerCLI code. The code selects a cluster and lists all the datastore available. The datastore with the most space available is selected for the virtual machine that is being deployed.
In the PowerCLI code, I just create a very simple virtual machine but you probably get the point. The magic is the $DS line that selects the datastore.
Requirements:
The PowerShell code is tested with the following VMware software components on Microsoft Windows:
- PowerCLI 6.5 Update 1
- VMware vCenter Server 6.0
### Variables
$CLUSTER = "Production" # A Cluster Name
$FOLDER = "Deployed VMs" # A Virtual Machine folder name located in the vCenter inventory
### Select datastores available and sort them on free space (select the one with most space free)
$DS = Get-Cluster -Name $CLUSTER | Get-Datastore | Select Name, FreeSpaceGB | Sort-Object FreeSpaceGB -Descending | Select -first 1
### Create a virtual machine called VM01
New-VM -Name VM01 -ResourcePool $CLUSTER -Datastore $DS.Name -Location $FOLDER -MemoryGB 1 -CD -DiskGB 5
Article update:
- 2018-07-30 – Added feature image.
- 2018-11-17 – Updated article to support the new standards of the website.