This Blog is to share our knowledge and expertise on Linux System Administration and VMware Administration

Wednesday, September 6, 2017

How to change the root password for all esxi hosts in a vcenter using script

The following script will change the root password for all esxi hosts in a vcenter. We should run the script using PowerCLI.

Before We  run the script you should create a scripts folder on the root of our C:\ drive and copy the script to there. We  need to have the current root password, the new root password and the name of the vCenter.

The script uses the Set-VMHostAccount cmdlet to change the root account password.

#Change Root Password Script for all hosts in a particular cluster

Copy the below code in a text file  and rename with passwd.ps1

#Prompt user for vCenter server and connect.
$vcenter = Read-Host "Enter vCenter Server: "
$vCenterUser = Read-Host "Enter your vCenter Username: "
$vCenterPw = Read-Host "Enter your vCenter Password: "

Connect-VIServer -Server $vcenter -User $vCenterUser -Password $vCenterPw

Write-Host "Connected to vCenter Server: $vcenter"

#Prompt user for datacenter and cluster
$datacenter = Read-Host "Enter Datacenter: "
$cluster = Read-Host "Enter Cluster: "
#Gather hosts from vCenter for chosen cluster

Write-Host "Getting hosts from datacenter..."

$MyVMHosts = Get-Datacenter $datacenter | Get-Cluster $cluster | Get-VMHost
# If we want to chnage for all ESXi hosts
# $MyVMHosts =Get-VMHost

#Disconnect from vCenter
Disconnect-VIServer -Confirm:$false
Write-Host "Got the hosts.  Next..."

#Prompt user for old root password and new password

$oldpassword = Read-Host "Enter onfiguration backup utility to download a backup of this to your management server. old root password: "
$newpassword = Read-Host "Enter new root password: "
$newpassword2 = Read-Host "Enter new root password again: "

#Connect to hosts and change root password, then disconnect.

if ($newpassword -eq $newpassword2){
    foreach ($line in $MyVMHosts) {
        Connect-VIServer -Server "$line" -User "root" -Password "$oldpassword" -WarningAction SilentlyContinue
        Set-VMHostAccount -UserAccount "root" -Password "$newpassword"
        Disconnect-VIServer -Confirm:$false
        Write-Host "$line...done."
}
}else{
 Write-Host "New passwords do not match!"
}

No comments:

Post a Comment