Powershell script to set the CDP settings for vsphere

I needed to turn on CDP on all hosts very quickly based on a request from out network guys

I could do all 30 hosts manually but decided to try in powershell. After few minutes of google around I found this site


I made a quick, and again very dirty, Powershell Script to turn on CDP on all hosts based on the code on that site. Because of the identical setup I could do it this way.

Again. As wit all powershell scripts:  this is going to hurt the eyes of a real PS scripter but hope it is os some use for someone..


function set-vSwitchLinkDiscovery {
    Param (
        #Switch to enable vSwitch Discovery On
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string] $vSwitchName = "vSwitch0",
        #Host on which the vSwitch Resides
        [Parameter(Mandatory=$true,HelpMessage="Need Host Name to connect with")] [string] $VMHost = "NoHostPassed"
    ) #Param

	$linkProtocol = "cdp"
	$linkOperation = "both"

	#Get the specification for the vSwitch
	$networkview = (get-vmhostnetwork -vmhost $VMHost | get-view)
	$vSwitchSpec = ($networkView.NetworkConfig.vSwitch | Where {$_.Name -eq $vSwitchName}).Spec

	#Set Protocol Type and Operation
	$vSwitchSpec.Bridge.LinkDiscoveryProtocolConfig.protocol = $linkProtocol
    $vSwitchSpec.Bridge.LinkDiscoveryProtocolConfig.operation = $linkOperation

	#Commit Changes
    "Updated " + $VMHost + "'s virtual switch " + $vSwitchName + " to do CDP"

# Set the VI Server and Filename before running
Connect-VIServer "vcenter5"
Write "Gathering VMHost objects"
# enkel zuela via : $vmhosts = Get-VMHost | Sort Name | Where-Object {$_.Name -match "zuela" } | Get-View
$vmhosts = Get-VMHost | Sort Name | Get-View
$MyCol = @()
foreach ($vmhost in $vmhosts){
 Write "****************"
 $ESXHost = $vmhost.Name
 Write "Collating information for $ESXHost"
 set-vSwitchLinkDiscovery -vmhost $ESXHost -vSwitchName "vSwitch0"
 set-vSwitchLinkDiscovery -vmhost $ESXHost -vSwitchName "vSwitch1"
 set-vSwitchLinkDiscovery -vmhost $ESXHost -vSwitchName "vSwitch2"
 Write "****************"

1 Comment

Leave a Reply

Your email address will not be published.