ya..know 它有点老了,但是让其他人尝试实现它来避免头痛。以下代码会将网络适配器分配给 VM 并设置 VLAN。请记住,我的 '_dataFields' 是带有虚拟机数据的结构,因此您必须在此处更改一些内容。
添加新的网络适配器并设置 VLAN
/// <summary>
/// For the given virtual machine, this sample adds a new Network Adapter device and
/// connects it to the specified switch. Note that in order to add a new Network Adapter
/// device to the virtual machine, the virtual machine must be in the power off state.
/// Also note that the maximum number of Network Adapter devices that may be configured
/// on a virtual machine is 8.
/// </summary>
public void ConnectVmToSwitch()
{
using (ManagementObject managementService = WmiUtils.GetVirtualMachineManagementService(_dataFields._scope))
//
// Find the Ethernet switch we want to connect to.
//
using (ManagementObject ethernetSwitch = NetworkUtils.FindEthernetSwitch(_dataFields.SwitchName, _dataFields._scope))
//
// Find the virtual machine we want to connect.
//
using (ManagementObject virtualMachine = WmiUtils.GetVirtualMachine(_dataFields.VmName, _dataFields._scope))
//
// Get the virtual machine's settings object which is used to make configuration changes.
//
using (ManagementObject virtualMachineSettings = WmiUtils.GetVirtualMachineSettings(virtualMachine))
//
// Add a new synthetic Network Adapter device to the virtual machine.
//
using (ManagementObject syntheticAdapter = NetworkUtils.AddSyntheticAdapter(virtualMachine, _dataFields._scope))
//
// Now that we have added a network adapter to the virtual machine we can configure its
// connection settings.
//
using (ManagementObject connectionSettingsToAdd = NetworkUtils.GetDefaultEthernetPortAllocationSettingData(_dataFields._scope))
{
connectionSettingsToAdd["Parent"] = syntheticAdapter.Path.Path;
connectionSettingsToAdd["HostResource"] = new string[] { ethernetSwitch.Path.Path };
//
// Now add the connection settings.
//
using (ManagementBaseObject addConnectionInParams = managementService.GetMethodParameters("AddResourceSettings"))
{
addConnectionInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
addConnectionInParams["ResourceSettings"] = new string[] { connectionSettingsToAdd.GetText(TextFormat.WmiDtd20) };
using (ManagementBaseObject addConnectionOutParams = managementService.InvokeMethod("AddResourceSettings", addConnectionInParams, null))
{
WmiUtils.ValidateOutput(addConnectionOutParams, _dataFields._scope);
if (_dataFields.VlanID > 0)
{
string[] syntheticAdapterResult = (string[])addConnectionOutParams["ResultingResourceSettings"]; // Msvm_EthernetPortAllocationSettingData return object
string syntheticAdapterPath = syntheticAdapterResult[0]; // Msvm_EthernetPortAllocationSettingData path
using (ManagementClass vlanSettingsData = new ManagementClass("Msvm_EthernetSwitchPortVlanSettingData"))
{
vlanSettingsData.Scope = _dataFields._scope;
using (ManagementObject vlanData = vlanSettingsData.CreateInstance())
{
vlanData["AccessVlanId"] = _dataFields.VlanID;
vlanData["OperationMode"] = (uint)_dataFields.VLANOperationalModes;
// Modify the VM settings.
using (ManagementBaseObject inParams = managementService.GetMethodParameters("AddFeatureSettings"))
{
inParams["AffectedConfiguration"] = syntheticAdapterPath;
inParams["FeatureSettings"] = new string[] { vlanData.GetText(TextFormat.CimDtd20) };
using (ManagementBaseObject outParams = managementService.InvokeMethod("AddFeatureSettings", inParams, null))
{
WmiUtils.ValidateOutput(outParams, _dataFields._scope);
}
}
}
}
}
}
}
}
}
将交换机分配给 VM 的原始代码来自 https://github.com/microsoft/Windows-classic-samples/blob/1d363ff4bd17d8e20415b92e2ee989d615cc0d91/Samples/Hyper-V/Networking/cs/ConnectVmToSwitch.cs,我刚刚对其进行了扩展以支持 VLAN 使用。我在调用中没有任何参数,因为所有数据都在结构中。
在 VM 上的现有网络适配器上添加/修改 VLAN
/// <summary>
/// Gets any virtual machine's management object
/// </summary>
/// <param name="managementObject">Any management object</param>
/// <returns>Any virtual machine's management object.</returns>
public static ManagementObject
GetVirtualMachineManagementObject(ManagementObject managementObject, string className)
{
using (ManagementObjectCollection settingsCollection = managementObject.GetRelated(className))
{
ManagementObject virtualMachineSettings = GetFirstObjectFromCollection(settingsCollection);
return virtualMachineSettings;
}
}
/// <summary>
/// For the given virtual machine, this sample will add / modfiy VLAN on existing network adapter
/// </summary>
public void SetVLANToVMNetworkAdapter()
{
ManagementObject syntheticAdapter = null;
bool vlanAlreadySet = false;
using (ManagementObject managementService = WmiUtils.GetVirtualMachineManagementService(_dataFields._scope))
//
// Find the virtual machine we want to connect.
//
using (ManagementObject virtualMachine = WmiUtils.GetVirtualMachine(_dataFields.VmName, _dataFields._scope))
//
// Now that we have added a network adapter to the virtual machine we can configure its
// connection settings.
//
using (ManagementObjectCollection findConnections = NetworkUtils.FindConnections(virtualMachine, _dataFields._scope))
{
if (findConnections.Count > 0)
{
foreach (ManagementObject connection in findConnections)
{
using (ManagementObjectCollection vmSwitches = connection.GetRelated("Msvm_SyntheticEthernetPortSettingData"))
{
if (vmSwitches.Count > 0)
{
foreach (ManagementObject vmSwitch in vmSwitches)
{
if (vmSwitch["ElementName"].ToString() == _dataFields.NetworkAdapterName)
{
//
// Got adapter on VM, lock it to connection object since we need connection path
// for vlan modifications
//
syntheticAdapter = connection;
//
// Got VLAN defiinition based on connection lock for vlan modifications
//
using (ManagementObjectCollection vmSwitcheVLANs = syntheticAdapter.GetRelated("Msvm_EthernetSwitchPortVlanSettingData"))
{
if (vmSwitcheVLANs.Count > 0)
vlanAlreadySet = true;
}
break;
}
}
}
}
}
}
if (syntheticAdapter != null && _dataFields.VlanID > 0)
{
string syntheticAdapterPath = syntheticAdapter.Path.Path;
if (vlanAlreadySet)
{
// VLAN is already set on adapter, change operation
// Modify the VM settings.
using (ManagementObject vlanData = WmiUtils.GetVirtualMachineManagementObject(syntheticAdapter, "Msvm_EthernetSwitchPortVlanSettingData"))
{
vlanData["AccessVlanId"] = _dataFields.VlanID;
vlanData["OperationMode"] = (uint)_dataFields.VLANOperationalModes;
using (ManagementBaseObject inParams = managementService.GetMethodParameters("ModifyFeatureSettings"))
{
inParams["FeatureSettings"] = new string[] { vlanData.GetText(TextFormat.CimDtd20) };
using (ManagementBaseObject outParams = managementService.InvokeMethod("ModifyFeatureSettings", inParams, null))
{
WmiUtils.ValidateOutput(outParams, _dataFields._scope);
}
}
}
}
else
{
using (ManagementClass vlanSettingsData = new ManagementClass("Msvm_EthernetSwitchPortVlanSettingData"))
{
vlanSettingsData.Scope = _dataFields._scope;
using (ManagementObject vlanData = vlanSettingsData.CreateInstance())
{
vlanData["AccessVlanId"] = _dataFields.VlanID;
vlanData["OperationMode"] = (uint)_dataFields.VLANOperationalModes;
using (ManagementBaseObject inParams = managementService.GetMethodParameters("AddFeatureSettings"))
{
inParams["AffectedConfiguration"] = syntheticAdapterPath;
inParams["FeatureSettings"] = new string[] { vlanData.GetText(TextFormat.CimDtd20) };
using (ManagementBaseObject outParams = managementService.InvokeMethod("AddFeatureSettings", inParams, null))
{
WmiUtils.ValidateOutput(outParams, _dataFields._scope);
}
}
}
}
}
}
}
}
从虚拟机上的网络适配器中删除 VLAN
/// <summary>
/// For the given virtual machine, this sample will delete VLAN on existing network adapter
/// </summary>
public void RemoveVLANFromVMNetworkAdapter()
{
using (ManagementObject managementService = WmiUtils.GetVirtualMachineManagementService(_dataFields._scope))
//
// Find the virtual machine we want to connect.
//
using (ManagementObject virtualMachine = WmiUtils.GetVirtualMachine(_dataFields.VmName, _dataFields._scope))
//
// Now that we have added a network adapter to the virtual machine we can configure its
// connection settings.
//
using (ManagementObjectCollection findConnections = NetworkUtils.FindConnections(virtualMachine, _dataFields._scope))
{
if (findConnections.Count > 0)
{
foreach (ManagementObject connection in findConnections)
{
// Get network adapter on virtual machine
using (ManagementObjectCollection vmSwitches = connection.GetRelated("Msvm_SyntheticEthernetPortSettingData"))
{
if (vmSwitches.Count > 0)
{
foreach (ManagementObject vmSwitch in vmSwitches)
{
if (vmSwitch["ElementName"].ToString() == _dataFields.NetworkAdapterName)
{
// Get vlan settings data from network adapter
using (ManagementObjectCollection vmSwitcheVLANs = connection.GetRelated("Msvm_EthernetSwitchPortVlanSettingData"))
{
if (vmSwitcheVLANs.Count > 0)
{
// Get first objecz
using (ManagementObject vlanData = WmiUtils.GetFirstObjectFromCollection(vmSwitcheVLANs))
{
using (ManagementBaseObject inParams = managementService.GetMethodParameters("RemoveFeatureSettings"))
{
// Remove it
inParams["FeatureSettings"] = new string[] { vlanData.Path.Path };
using (ManagementBaseObject outParams = managementService.InvokeMethod("RemoveFeatureSettings", inParams, null))
{
WmiUtils.ValidateOutput(outParams, _dataFields._scope);
}
}
}
}
}
}
}
}
}
}
}
}
}
请记住,我不使用通用网络适配器名称,我在创建 VM 时使用个性化的名称。这样我可以在需要时轻松获取适配器数据。
想要为适配器添加个性化名称的人可以编辑 AddSyntheticAdapter(ManagementObject virtualMachine, ManagementScope scope) 函数,并在 adapterToAdd["ElementName"] 对象中包含不同的名称。
希望这对通过 WMI 进行开发的勇敢者有所帮助! :)