Search code examples
powershellvirtual-machinevmwarepowershell-4.0powercli

How to write Nested Loop in Power shell


I want to compare virtual machine ProvisionedSpaceGB with datastore FreespaceGB if ProvisionedSpaceGB is less than datastore free space then it should be space is available else space not available.

My below code is working as expected for single virtual machine but I want to do this for multiple VMs.

#will be printing datastore FreeSpace for respective vms 
$PrintDatastore_Fsize = Get-Vm -Name Terminal1 |
                        Get-Datastore |
                        select FreeSpaceGB

#will be printing  ProvisionedSpace respective vms 
$getvmspace = Get-Vm -Name Terminal1 |
              select ProvisionedSpaceGB

if (($PrintDatastore_Fsize).FreeSpaceGB -gt ($getvmspace).ProvisionedSpaceGB) {
    "Space is available"
} else {
    "space is not available"
}

How can I write a nested loop for the below code in PowerShell. my above code is working fine for a single VM but looks like for multiple VM it's not working only accepting one condition.

$vmList = Get-Content "C:\Program Files (x86)\VMware\scripting\vmlist.txt"
foreach ($PrintDatastore_Fsize in $vmList) {
    Get-Vm -Name $PrintDatastore_Fsize |
        Get-Datastore |
        select FreeSpaceGB
}

foreach ($getvmspace in $vmList) {
    Get-Vm -Name $getvmspace |
        select ProvisionedSpaceGB
}

if (($PrintDatastore_Fsize).FreeSpaceGB -gt ($getvmspace).ProvisionedSpaceGB) {
    Write-Host "Space is available"
} else {
    Write-Host "space is not available"
}

Solution

  • Actually, you do not need a nested loop ... It's a bit late and If I am not mistaking something, you may try the following:

    $vmList = Get-Content "C:\Program Files (x86)\VMware\scripting\vmlist.txt"
    foreach ($VMName in $vmList) {
        $VM = Get-Vm -Name $VMName
        $VMDataStore = $VM | Get-Datastore
        if ($VMDataStore.FreeSpaceGB -gt $VM.ProvisionedSpaceGB) {$SpaceAvailable = $true}
        else { $SpaceAvailable = $false}
        [PSCustomObject]@{
            VMName = $VMName
            ProvisionedSpace = $VM.ProvisionedSpaceGB
            FreeSpace = $VMDataStore.FreeSpaceGB
            SpaceAvailable = $SpaceAvailable
        }
    
    }