private static ManagementPath CreateSwitchPortForVm(ComputerSystem vm, VirtualSwitchManagementService vmNetMgmtSvc, VirtualSwitch vSwitch) { ManagementPath newSwitchPath = null; var ret_val = vmNetMgmtSvc.CreateSwitchPort( vm.ElementName, Guid.NewGuid().ToString(), "", vSwitch.Path, out newSwitchPath); // Job is always done synchronously if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to create switch for NIC on VM {0} (GUID {1}), error code {2}", vm.ElementName, vm.Name, ret_val); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } return newSwitchPath; }
// add vlan support by setting AccessVLAN on VLANEndpointSettingData for port private static void SetPortVlan(string vlan, VirtualSwitchManagementService vmNetMgmtSvc, ManagementPath newSwitchPath) { logger.DebugFormat("Setting VLAN to {0}", vlan); VLANEndpointSettingData vlanEndpointSettings = GetVlanEndpointSettings(vmNetMgmtSvc, newSwitchPath); vlanEndpointSettings.LateBoundObject["AccessVLAN"] = vlan; vlanEndpointSettings.CommitObject(); }
public static VLANEndpointSettingData GetVlanEndpointSettings(VirtualSwitchManagementService vmNetMgmtSvc, ManagementPath newSwitchPath) { // Get Msvm_VLANEndpoint through associated with new Port var vlanEndpointQuery = new RelatedObjectQuery(newSwitchPath.Path, VLANEndpoint.CreatedClassName); var vlanEndpointSearch = new ManagementObjectSearcher(vmNetMgmtSvc.Scope, vlanEndpointQuery); var vlanEndpointCollection = new VLANEndpoint.VLANEndpointCollection(vlanEndpointSearch.Get()); // assert if (vlanEndpointCollection.Count != 1) { var errMsg = string.Format("No VLANs for vSwitch on Hyper-V server for switch {0}", newSwitchPath.Path); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } VLANEndpoint vlanEndpoint = vlanEndpointCollection.OfType<VLANEndpoint>().First(); // Get Msvm_VLANEndpointSettingData assocaited with Msvm_VLANEndpoint var vlanEndpointSettingsQuery = new RelatedObjectQuery(vlanEndpoint.Path.Path, VLANEndpointSettingData.CreatedClassName); var vlanEndpointSettingsSearch = new ManagementObjectSearcher(vmNetMgmtSvc.Scope, vlanEndpointSettingsQuery); var vlanEndpointSettingsCollection = new VLANEndpointSettingData.VLANEndpointSettingDataCollection(vlanEndpointSettingsSearch.Get()); // assert if (vlanEndpointSettingsCollection.Count != 1) { var errMsg = string.Format("Internal error, VLAN for vSwitch not setup propertly Hyper-V"); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } VLANEndpointSettingData vlanEndpointSettings = vlanEndpointSettingsCollection.OfType<VLANEndpointSettingData>().First(); return vlanEndpointSettings; }