Del via


Adding a Network Adapter To A VM Using The Hyper-V WMI V2 Namespace

I have had a number of folks ask how to utilize the root\virtualization\v2 namespace to add a network adapter to a VM… 

 

For some more information take a look at the following MSDN pages: Networking service, Sample: Querying networking objects.

 

 

$vmName = "Test"

#Retrieve the Hyper-V Management Service, The ComputerSystem class for the VM and the VM’s SettingData class.
$Msvm_VirtualSystemManagementService = Get-WmiObject -Namespace root\virtualization\v2 ` 
      -Class Msvm_VirtualSystemManagementService

$Msvm_ComputerSystem = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem `
      -Filter "ElementName='$vmName'"

$Msvm_VirtualSystemSettingData = ($Msvm_ComputerSystem.GetRelated("Msvm_VirtualSystemSettingData", `
"Msvm_SettingsDefineState", `
      $null, `
      $null, `
"SettingData", `
"ManagedElement", `
      $false, $null) | % {$_})

#Retrieve the default (primordial) resource pool for Synthetic Ethernet Port’s
$Msvm_ResourcePool = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ResourcePool `
      -Filter "ResourceSubType = 'Microsoft:Hyper-V:Synthetic Ethernet Port' and Primordial = True"

#Retrieve the AllocationCapabilities class for the Resource Pool
$Msvm_AllocationCapabilities = ($Msvm_ResourcePool.GetRelated("Msvm_AllocationCapabilities", `
"Msvm_ElementCapabilities", `
      $null, `
      $null, `
      $null, `
      $null, `
      $false, `
      $null) | % {$_})

#Query the relationships on the AllocationCapabilities class and find the default class (ValueRole = 0)
$Msvm_SettingsDefineCapabilities = ($Msvm_AllocationCapabilities.GetRelationships(`
"Msvm_SettingsDefineCapabilities") | Where-Object {$_.ValueRole -eq "0"})

#The PartComponent is the Default SyntheticEthernetPortSettingData class values
$Msvm_SyntheticEthernetPortSettingData = [WMI]$Msvm_SettingsDefineCapabilities.PartComponent

#Specify a unique identifier, a friendly name and specify dynamic mac addresses
$Msvm_SyntheticEthernetPortSettingData.VirtualSystemIdentifiers = [Guid]::NewGuid().ToString("B")
$Msvm_SyntheticEthernetPortSettingData.ElementName = "Network Adapter"
$Msvm_SyntheticEthernetPortSettingData.StaticMacAddress = $false

#Add the network adapter to the VM
$Msvm_VirtualSystemManagementService.AddResourceSettings($Msvm_VirtualSystemSettingData, `
      $Msvm_SyntheticEthernetPortSettingData.GetText(2))

 

-Taylor Brown
-Program Manager, Hyper-V

Comments

  • Anonymous
    July 01, 2014
    Hi, everything looks OK but AddResourceSettings returns 4096. Does it work for you? I am trying it from another machine and I have added -Computername to class creations etc.

  • Anonymous
    August 20, 2014
    The comment has been removed