Hyper-V How To: Add a Virtual NIC to a VM using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for adding a virtual NIC to a VM:

# Add a NIC (synthetic ethernet port) to a virtual machine

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

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

# Allocate the new ethernet port
$allocationCapabilities = gwmi -namespace root\virtualization Msvm_AllocationCapabilities `
    -filter "ResourceType = 10 AND ResourceSubtype = 'Microsoft Synthetic Ethernet Port'"
$allocationPath = $allocationCapabilities.__PATH.replace("\","\\")
$default = gwmi -namespace root\virtualization Msvm_SettingsDefineCapabilities `
    -filter "ValueRange = 0 AND GroupComponent = '$allocationPath'"

$synthEth = [wmi]$default.PartComponent
$synthEth.ElementName = $ethPortName
$newGuid = [System.Guid]::NewGuid().Guid
$synthEth.VirtualSystemIdentifiers = @("{$newGuid}")

# Attach the new NIC (ethernet port) to the virtual machine
$vmms = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService

$result = $vmms.AddVirtualSystemResources($vm,@($synthEth.GetText(1)))

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