PowerCLIvHerseyVMware

Create a new Datacenter and Add ESXi Hosts with PowerCLI

I just a few days I will have been at my gig at ABS Technology Architects for a year. In that short time I have taken part in multiple new vSphere implementations. To help maintain configuration consistency and to speed up implementations I have written a set of PowerCLI scripts. I am going to share these scripts here in a series of posts.

This first PowerCLI script creates a new Data Center in vCenter inventory and adds a list of ESXi hosts to the new Data Center.

To use the script first set the variable $datacenter to the name of the new Data Center that should be created. Then set the variable $esxhosts to a comma separated list of the ESXi hosts ip addresses or ESXi hosts FQDNs that will be added to the new Data Center.

Once the variables are set save the script and connect a PowerCLI session to the vCenter Server using the Connect-VIServer PowerCLI Cmdlet and run the script. The script will first prompt for the ESXi credentials to use (the credentials must be the same for all ESXi hosts being added). The script will then create the new Data Center and loop through the hosts defined in $esxhosts adding each of them to the newly created Data Center.

# Create a new Data Center and Add ESXi Host to the new Data Center
# PowerCLI Session must be connected to vCenter Server using Connect-VIServer

# Name of the new Data Center
$datacenter = "LAB"

# List of ESXi Hosts to Add to New Data Center
# Use the IP Addresses or FQDNs of the ESXi hosts to be added
# Example using IP: $esxhosts = "192.168.1.25","192.168.1.26"
# Example using FQDN: $esxhosts = "esx0.lab.local","esx1.lab.local"
$esxhosts = "192.168.1.25"

# Prompt for ESXi Root Credentials
$esxcred = Get-Credential 

Write-Host "Creating Datacenter $datacenter" -ForegroundColor green
$location = Get-Folder -NoRecursion
New-DataCenter -Location $location -Name $datacenter

foreach ($esx in $esxhosts) {
  Write-Host "Adding ESX Host $esx to $datacenter" -ForegroundColor green
  Add-VMHost -Name $esx -Location (Get-Datacenter $datacenter) -Credential $esxcred -Force -RunAsync -Confirm:$false
}

Write-Host "Done!" -ForegroundColor green

Nothing real fancy here but the script does help speed up adding ESXi hosts to the vCenter inventory. Hope you find it useful. Any comments or suggestions for improvements are welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

fourteen − 11 =