VMware Cloud Community
tdubb123
Expert
Expert

script runs slow

any idea how to optimize this. runs very slow

 

$results = @()
$ds = get-datastore -server vcenterserver -name xxxx
 

foreach ($d in $ds) {
 
$vms = get-datastore $d | get-vm
 
foreach ($vm in $vms){
 
$cluster = get-cluster -vm $vm
$result = "" | select Datastore, Vmname, powerstate, cluster, datacenter, CapacityGB
$result.Datastore = $d.name
$result.vmName = $vm.name
$result.powerstate = $vm.powerstate
$result.cluster = $cluster.name
$result.datacenter = $d.datacenter
$result.CapacityGB = $d.CapacityGB

$results += $result
}
}

$results | ft -AutoSize
Reply
0 Kudos
8 Replies
LucD
Leadership
Leadership

Where do you populate $vms?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
tdubb123
Expert
Expert

right after the first for loop

Reply
0 Kudos
LucD
Leadership
Leadership

That line wasn't there in the original post.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
tdubb123
Expert
Expert

i edited it

Reply
0 Kudos
kwhornlcs
Enthusiast
Enthusiast

You shouldn't need that second get-datastore (bolded below) $d should already be a datastore object. Could be changed to either 
$vms = $d | Get-VM -OR - $vms = Get-VM -Datastore $d
 
...
foreach
 ($d in $ds) {
$vms = get-datastore $d | get-vm
foreach ($vm in $vms){
$cluster = get-cluster -vm $vm
...

EDIT: - you can also make the cluster a calculated property off $vm as so:
$result.cluster = $vm.VMHost.Parent.Name
Reply
0 Kudos
LucD
Leadership
Leadership

Try something like this

Updated the Cluster calculation method!

 

Get-View -ViewType Datacenter -Property 'Name' -PipelineVariable dc |
ForEach-Object -Process {
  Get-View -ViewType Datastore -SearchRoot $dc.MoRef -Property 'Name','Summary.Capacity','VM' -Filter @{VM='.'} -PipelineVariable ds |
  ForEach-Object -Process {
    Get-View -Id $ds.VM |
    ForEach-Object -Process {
      [PSCustomObject]@{
        Datastore = $ds.name
        VMName = $_.name
        PowerState = $_.Runtime.PowerState
        Cluster = (Get-View -Id (Get-View -Id $_.Runtime.Host -Property Parent).Parent -Property Name).Where{$_ -is [VMware.Vim.ClusterComputeResource]}.Name
        Datacenter = $dc.Name
        CapacityGB = [math]::Round($ds.Summary.Capacity/1GB,2)
      }
    }
  }
} | Format-Table -AutoSize

 

 


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
tdubb123
Expert
Expert

thank Luc. how do i filter based on a a vcenter and datastore names?

Reply
0 Kudos
LucD
Leadership
Leadership

To filter on one or more vCenters, use the Server parameter on the Get-View cmdlets.

To filter on Datastore names, use the Filter parameter.

Get-View -ViewType Datastore -SearchRoot $dc.MoRef -Property 'Name','Summary.Capacity','VM' -Filter @{VM='.';Name='ds1|ds2|ds3'} -PipelineVariable ds |


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos