I wrote a nice short script to move any VMs that had a thick disk format to a datastore and make it thin. Here is what I have:
#Simple line, just getting the VMs with a thick HD and saving it to a variable
$thickVMs = Get-VM | where { ($_ | Get-HardDisk).storageformat -eq "Thick" }
#Here is what I needed. Because we have different datacenters, I needed to make sure the VM was getting moved to a datastore within its own datacenter, so for the current VM, I retrieved it's current host, and the datastores that it sees. Then I had
#to make sure that the datastore wasn't one named "ISOs", and that it wasn't the current datastore where the VM is now. Then I needed to choose the datastore with the most freespace, and move the VM there and make it thin.
foreach ($VM in $thickVMs) {
Move-VM -VM $VM -Datastore ( $vm | Get-VMHost | Get-Datastore | where { ($_.name) -ne "ISOs" -and $_.name -ne ($vm | Get-Datastore) } | sort FreespaceGB -Descending | select -First 1) -DiskStorageFormat Thin
}
I tested it out with some small test VMs, and everything appeared to work, but when I ran the script, and this was hours later, what I found out was that everything was going to 1 datastore. The "sort FreespaceGB -Descending | select -First 1" section isn't changing to a new datastore that has more space, it only selected the first one that had more space, and VMs were moved there, and the datastore almost filled up.
I just don't understand why this happened. I thought that it would loop to each new VM, get the current datastore with the most space, and dynamically change as the datastore freespace changed. What am I missing?