Hyper-V How to: Remove Virtual NIC using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for removing virtual NICs from your VMs:

# Remove a NIC (synthetic ethernet port) from a virtual machine

    [string]$vmName = $(throw "Must specify virtual machine name"),
    [string]$ethPortName = $(throw "Must specify virtual NIC name")

$vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName='$vmName'"

# Find the NIC from the virtual system setting data
$vssd = gwmi -namespace root\virtualization `
    -query "Associators of {$vm} where ResultClass = Msvm_VirtualSystemSettingData" |`
    where{$_.SettingType -eq 3}
$synthEth = gwmi -namespace root\virtualization `
    -query "Associators of {$vssd} where ResultClass = Msvm_SyntheticEthernetPortSettingData" |`
    where{$_.ElementName -eq $ethPortName}

# Remove the NIC using the method available on the service
$vmms = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService

$result = $vmms.RemoveVirtualSystemResources($vm,@($synthEth))

if($result.ReturnValue -eq 4096){
    # A Job was started, and can be tracked using its Msvm_Job instance
    $job = [wmi]$result.Job
    # Wait for job to finish
    while($job.jobstate -lt 7){$job.get()}
    # Return the Job's error code
    return $job.ErrorCode
# Otherwise, the method completed
return $result.ReturnValue

For more info on how to use PS cmdlets see: http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx

See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and... documentation!

For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V PowerShell Example Scripts.zip-download

Comments (0)

Skip to main content