Hi guys,
I'm learning PowerShell to automate some processes and my first experiment is making a script to deploy multiple VMs from templates.
My code at the moment just lists available host datastores and the templates available, and this list is produce by iterating through arrays returned by the Get-Template and Get-Datastore cmdlets.
I having difficulty doing the same for Get-VMHost as this doesn't seem to return an array, and the final block of code below errors with:
Unable to index into an object of type VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl.
Is there another cmdlet I can use that returns an array.
Here is the code block
Write-Host "`nPlease enter ESXi host or vCenter IP Address / Name`n"
$server = Read-Host
$connect = Connect-VIServer $server
# Get available templates
$nameOfTemplate = Get-Template
$numberOfTemplate = $nameOfTemplate.Count
Write-Host "`nAvailable Templates`n"
$i = 0
do {Write-Host $i "- " $nameOfTemplate[$i]; $i++}
while ($i -lt $numberOfTemplate)
# Get available Datastores
$nameOfDatastore = Get-Datastore
$numberOfDatastore = $nameOfDatastore.Count
Write-Host "`nAvailable Templates`n"
$i = 0
do {Write-Host $i "- " $nameOfDatastore[$i]; $i++}
while ($i -lt $numberOfDatastore)
# Get usable hosts
$nameOfHost = Get-VMHost | where {$_.ConnectionState -eq "Connected"}
$numberOfDatastore = $nameOfDatastore.Count
Write-Host "`nAvailable Templates`n"
$i = 0
do {Write-Host $i "- " $nameOfDatastore[$i]; $i++}
while ($i -lt $numberOfDatastore)
Disconnect-VIServer $server
I suspect your problem is coming from the fact that there is only 1 VMHost returned.
In that case the $nameOfHost variable is not an array, and hence the "indexing" will not work.
You can force an array like this
$nameOfHost= @(Get-VMHost |where{$_.ConnectionState -eq "Connected"})
But you would still need to take care of a $null or empty array.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Discussion moved from VMware ESXi 5 to VMware vSphere™ PowerCLI
I suspect your problem is coming from the fact that there is only 1 VMHost returned.
In that case the $nameOfHost variable is not an array, and hence the "indexing" will not work.
You can force an array like this
$nameOfHost= @(Get-VMHost |where{$_.ConnectionState -eq "Connected"})
But you would still need to take care of a $null or empty array.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thank you.
Sorry I copied an pasted the wrong block of code for the Get usable hosts, but you understood anyway.
Thanks.