Thursday, May 24, 2012

PowerCLI - Change virtual NIC device connectivity

More on manipulating VM nics using PowerCLI. The connectivity of the NIC of a VM can be controlled by using the folllowing flags:
connected - specifies whether the NIC is connected or not to the portgroup (valid only for started VMs)
startConnected - specifies whether the device will be connected when the VM starts or not
allowGuestControl - allows the guest to control whether the device is connected or not

To do it,  you can use the vSphere Client, but if you are talking about  more than one VM then the following code is better:

$vmlist = Import-Csv "H:\Scripts\vmlist.txt"

foreach ($row in $vmlist) {
foreach ($netif in get-networkadapter $row.VMname) {
if ($netif.NetworkName -ne "pg_vm_admin"){
Set-NetworkAdapter -NetworkAdapter $netif -StartConnected:$false -Confirm:$false
}
}
}

The code gets a list of powered off VMs and for each one it gets its network adapters. If the network adapter is connected to any other network except administration, it disconnects it. After that I could start up the VMs to see what I was dealing with. 


Another usage is to check the power state of the VM and if the VM is on then disconnect it from the network:

$vmlist = Import-Csv "H:\Scripts\vmlist.txt"

foreach ($row in $vmlist) {
$vm = get-vm $row.VMname

if ($vm.PowerState -eq "PoweredOn") {
foreach ($netif in get-networkadapter $vm) {
if ($netif.NetworkName -ne "pg_vm_admin"){
Set-NetworkAdapter -NetworkAdapter $netif -Connected:$false -Confirm:$false
}
}
}
}

No comments: