Isn’t that a mouthful for a title ? I can feel my SEO plugin complaining at me as I write this ;) This is a short and simple script that will examine the VMs in your infrastructure and remove the network adapters from them that are attached to specific portgroups. It came in handy as we were decommissioning a network and wanted to remove the adapter from our multi-honed VMs.
As noted in the script, this has been made possible by LucD’s code in his answer on the VMware communities site (link below). I’ve only wrapped it up to only apply to certain VMs.
This script takes two parameters:
- VMName - this is used as an argument to Get-VM, so it can be used to get more than one VM.
- NetworkName - this will match any portgroups that start with the same string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
param([string] $VMName,
[Parameter(Mandatory=$true)][string] $NetworkName)
<#
param: vm name. if blank, get them all.
param: network name. to match the name of the network to remove.
Uses code from LucD from the following location:
https://communities.vmware.com/t5/VMware-PowerCLI-Discussions/Remove-network-adapter-from-running-vm/td-p/1269138
#>
# Ensure connected.
if ($global:DefaultVIServers.Count -eq 0) {
Write-Output "There are no connected VI Servers. Connect to one using Connect-VIServer and then run this script again.";
exit;
}
# Get the VMs
$vms = @();
if ($null -ne $VMName -And $VMName.Length -gt 0) {
$vms = Get-VM $VMName;
} else {
$vms = Get-VM | Sort-Object Name;
}
# Loop through the VMs and disconnect any found adapters.
$vms | ForEach-Object {
$vm = $_;
$adapters = $vm | Get-NetworkAdapter | Where-Object { $_.NetworkName.StartsWith($NetworkName); }
if ($null -ne $adapters) {
$adapters | ForEach-Object {
$adapter_name = $_.Name;
$nic = $vm.ExtensionData.Config.Hardware.Device | Where-Object {$_.DeviceInfo.Label -eq $adapter_name };
if ($null -ne $nic) {
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec;
$dev = New-Object VMware.Vim.VirtualDeviceConfigSpec;
$dev.operation = "remove";
$dev.Device = $nic;
$spec.DeviceChange += $dev;
Write-Output "$($vm.Name) - disconnecting $adapter_name";
$vm.ExtensionData.ReconfigVM($spec);
}
}
}
}
|
The script is also available in my library - hosted at https://github.com/nelons/psscripts.
Also, yes, the SEO plugin told me the title was too long. Oh well !