VMware Cloud Community
Afro201110141
Contributor
Contributor
Jump to solution

Powershell help

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

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

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

View solution in original post

Reply
0 Kudos
3 Replies
a_p_
Leadership
Leadership
Jump to solution

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

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

Reply
0 Kudos
Afro201110141
Contributor
Contributor
Jump to solution

Thank you.

Sorry I copied an pasted the wrong block of code for the Get usable hosts, but you understood anyway.

Thanks.

Reply
0 Kudos