Change Guest VM IP from Hyper-V Host

2
5381
PowerShell

Since Windows Server 2012, Microsoft introduces the ability to change or inject IP configuration of Guest VM from its HyperV host. This feature is using Msvm_GuestNetworkAdapterConfiguration class.

Below is the PowerShell Script from itprotoday to change/inject the Guest VM IP. Replace the name of the VM as needed and the IP configuration.

 $vmName = "win81g2"
 $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) | % {$_})
 $Msvm_SyntheticEthernetPortSettingData = $Msvm_VirtualSystemSettingData.GetRelated("Msvm_SyntheticEthernetPortSettingData")
 $Msvm_GuestNetworkAdapterConfiguration = ($Msvm_SyntheticEthernetPortSettingData.GetRelated("Msvm_GuestNetworkAdapterConfiguration", "Msvm_SettingDataComponent",$null, $null, "PartComponent", "GroupComponent", $false, $null) | % {$_})
 $Msvm_GuestNetworkAdapterConfiguration.DHCPEnabled = $false
 $Msvm_GuestNetworkAdapterConfiguration.IPAddresses = @("192.168.1.207")
 $Msvm_GuestNetworkAdapterConfiguration.Subnets = @("255.255.255.0")
 $Msvm_GuestNetworkAdapterConfiguration.DefaultGateways = @("192.168.1.1")
 $Msvm_GuestNetworkAdapterConfiguration.DNSServers = @("192.168.1.10", "192.168.1.11")
 $Msvm_VirtualSystemManagementService.SetGuestNetworkAdapterConfiguration($Msvm_ComputerSystem.Path, $Msvm_GuestNetworkAdapterConfiguration.GetText(1))

If you want to set the IP configuration to DHCP, you can change the DHCPEnabled to $true and omit the IP address, Subnets, and Default Gateways.

If the operation is performed asynchronously, this method will return 4096.

Return value


This method returns one of the following values.

  • Completed with No Error (0)
  • Method Parameters Checked – Job Started (4096)
  • Failed (32768)
  • Access Denied (32769)
  • Not Supported (32770)
  • Status is unknown (32771)
  • Timeout (32772)
  • Invalid parameter (32773)
  • System is in use (32774)
  • Invalid state for this operation (32775)
  • Incorrect data type (32776)
  • System is not available (32777)
  • Out of memory (32778)

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here