I'm working on a deployment script for VMs on a VMWare platform but I'm stuck.
Basically, my script does this:
Receive information from Excel and first runs some check. It does that for each row, which will represent VM information, before any VM is created.
When all VMs are validated, the first VM will be created, and then the next one, etc.
One of my functions will calculate the best available storage disk. It returns the first storage disk with the most available diskspace.
That function looks like this:
Function Get-AvailableStorage {
$Threshold = "80" # GB
$TotalFreeSpace = Get-Cluster -Name Management |
Get-Datastore |
where Name -notlike "*local*" |
sort FreeSpaceGB -Descending
if ($SqlServices -notlike "NONE") {
$VMSize = 30 + $VMStorage + 10
} else {
$VMSize = 30 + $VMStorage
}
foreach ($StorageDisk in $TotalFreeSpace) {
[math]::floor($StorageDisk.FreeSpaceGB) | Set-Variable RoundedSpace
$FreeAfter = $RoundedSpace - $VMSize | sort -Descending
if ($FreeAfter -lt $Threshold) {
return $StoragePool = "VSAN"
} else {
return $StorageDisk.Name
}
}
}
The problem
When I have multiple VMs in my Excel, the storage disk is always the same, because the available diskspace is not being updated (because none of the VMs is being deployed yet).
I did some investigation on my own:
I have to figure out a way to update the column FreeSpaceGB
but that is a ReadOnly property.
I then though to push every item in another array which I created myself but that also doesn't work. Still Readonly property.
Then I thought about using PSObject
with an Add-Member
, but I cannot get that working either (or I'm doing it wrong).
$ownarray= @()
$item = New-Object PSObject
$Global:TotalFreeSpaceManagement = Get-Cluster -Name Management |
Get-Datastore |
where Name -notlike "*local*" |
sort FreeSpaceGB -Descending
foreach ($StorageDisk in $Global:TotalFreeSpaceManagement) {
$item | Add-Member -Type NoteProperty -Name "$($StorageDisk.Name)" -Value "$($StorageDisk.FreeSpaceGB)"
$ownarray += $item
}
UPDATE
I use the hashtable like @Ansgar suggested. When I try it manually it's working perfectly, but in my script it's not. When I have multiple VMs in an array, the previous datastore is being used and the space that is left is UPDATED.
Example:
VM1 is 120GB and uses VM-105. That disk has 299GB left.
VM2 is 130GB and uses VM-105. Then the disk has 289GB left.
Both VMs are getting suggested VM-105 based on the most free space.
VM-105 should have 299 - 130 = 160GB left is the script was working correct but somehow the $FreeSpace
is updated, or $max
is overwritten, and I cannot figure how this happens.