Tuesday, October 6, 2009

Configuring Network with PowerCLI and .CSV File

A couple of weeks ago I was in need to configure several new ESX servers with multiple NICs, vSwitches, and VLANs. Since I'm not one to do the same thing over and over again I turned to scripting. To further complicate things I wanted to allow the same script to create vSwitches, configure vMotion switch, add port groups, and create NIC Teams all from a prepopulated .CSV file. I'm doing this primarily so that all configuration could be done before the server arrived and so that I could create "Switch Profiles" when I add new hosts to clusters.

In the end I developed a script that reads from a .CSV file and then creates the desired switching. The first column tells the script what type of addition it is and the script processes the information for that object accordingly. I've noticed a few others have been posting recently about scripts on setting up portgroups, etc. and thought it was time to no longer keep this to myself (i.e. finally found the time to post). I too would like to also credit Hal Rottenburg's book Managing VMware Infrastructure with Windows Powershell which was very helpful for this and many other scripting projects I will be posting soon. Mike Laverick's post linked below helped in configuring the vMotion switch.

I hope you find this helpful. It has been HUGE in my environment.

Download the files here:

Links where others discuss switch configuration with PowerCLI.

Text of Script w/out comments

$getinfo = Import-Csv "\\server\share\file.csv"
Connect-VIServer -Server vCenterServer

$getinfo | % {
$Type = $_.Type #!!!! Case Sensitive !!!!!!
$gethost = Get-VMHost -Name $_.HostName
$SwitchName = $_.SwitchName
$PortGroup = $_.PortGroupName
$Nic = $_.NIC
$IP = $_.IP
$Subnet = $_.Subnet
$kernelGW = $_.KernelGW

If ($Type -eq "Switch") {
$gethost | New-VirtualSwitch -Name $SwitchName -Nic $Nic
If ($Type -ne "vMotion") {
$getswitch = Get-VirtualSwitch -VMHost $gethost -Name $SwitchName
If ($Type -eq "Team"){
$getswitch | Set-VirtualSwitch -Nic $Nic
IF ($Type -eq "Portgroup") {
$getswitch | New-VirtualPortGroup $PortGroup -VLanId $VLAN
IF ($Type -eq "vMotion") {

$newvswitch = New-VirtualSwitch -VMHost $gethost -Name $SwitchName -Nic $Nic
$vmotion = New-VirtualPortGroup -VirtualSwitch $newvswitch -Name $PortGroup
New-VMHostNetworkAdapter -VMHost $gethost -PortGroup $PortGroup -VirtualSwitch $newvswitch -IP $IP -SubnetMask $subnet -VMotionEnabled: $true

$vmhostnetwork = get-vmhostnetwork $gethost
set-vmhostnetwork -network $vmhostnetwork -vmkernelgateway $kernelGW

No comments:

Post a Comment