Change root password on all vSphere ESXi hosts

Adapted from Change root password on all (or some) vSphere h… | VMware Communities.

$vCenter = "vcenterserver"
$oldpw = "oldpwd"
$newpw = "newpwd"

connect-viserver -server $vCenter -Credential (Get-Credential)
$hosts = @() 
write-host "Querying for ESXi hosts..."

Get-VMHost | sort | Where {$_.ConnectionState -eq "Connected" -or $_.ConnectionState -eq "Maintenance"} | Get-View | Where {$_.Summary.Config.Product.Name -match "i"} | % { $hosts+= $_.Name }

Disconnect-VIServer -confirm:$false

foreach ($vmhost in $hosts) {
    write-host "Connecting to $vmhost..."
    connect-viserver -server $vmhost -user root -password "$oldpw"
    write-host "Changing root password on $vmhost..."
    Set-VMHostAccount -UserAccount root -password "$newpw"
    Disconnect-VIServer -confirm:$false
}