ModifySwitchName(
            string existingSwitchName,
            string newSwitchName,
            string newNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Get the switch we want to modify.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(existingSwitchName, scope))

                //
                // To make modifications to the switch, we need to modify its configuration object.
                //
                using (ManagementObject ethernetSwitchSettings = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                {
                    //
                    // Modify its properties as desired.
                    //
                    ethernetSwitchSettings["ElementName"] = newSwitchName;
                    ethernetSwitchSettings["Notes"]       = new string[] { newNotes };

                    //
                    // This is how you can modify the IOV Preferred property from its current value.
                    // We leave this commented out because it could potentially fail for a system that doesn't
                    // support IOV.
                    //
                    // ethernetSwitchSettings["IOVPreferred"] = !((bool)ethernetSwitchSettings["IOVPreferred"]);

                    //
                    // Now call the ModifySystemSettings method to apply the changes.
                    //
                    using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                        using (ManagementBaseObject inParams = switchService.GetMethodParameters("ModifySystemSettings"))
                        {
                            inParams["SystemSettings"] = ethernetSwitchSettings.GetText(TextFormat.WmiDtd20);

                            using (ManagementBaseObject outParams =
                                       switchService.InvokeMethod("ModifySystemSettings", inParams, null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The switch '{0}' was renamed to '{1}' successfully.",
                                            existingSwitchName, newSwitchName));
        }
Пример #2
0
 internal void DefineSystem(ManagementObject systemSettings, ManagementObject[] resourceSettings, out ManagementObject resultingSystem)
 {
     using (ManagementBaseObject inputParameters = vmms.GetMethodParameters("DefineSystem"))
     {
         inputParameters["SystemSettings"]   = systemSettings.GetText(TextFormat.WmiDtd20);
         inputParameters["ResourceSettings"] = resourceSettings.ToStringArray();
         using (ManagementBaseObject outputParameters = vmms.InvokeMethod("DefineSystem", inputParameters, null))
         {
             ValidateOutput(outputParameters);
             resultingSystem = new ManagementObject((string)outputParameters["ResultingSystem"]);
         }
     }
 }
Пример #3
0
        VmAndStorageMigrationSimple(
            string sourceHost,
            string destinationHost,
            string vmName
            )
        {
            ManagementScope srcScope = new ManagementScope(
                @"\\" + sourceHost + @"\root\virtualization\v2", null);

            using (ManagementObject migrationSettingData = GetMigrationSettingData(srcScope))
                using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, srcScope))
                {
                    migrationSettingData["MigrationType"] = MigrationType.VirtualSystemAndStorage;
                    migrationSettingData["TransportType"] = TransportType.TCP;

                    // Get the VHD SASDs.
                    string[]           sasds   = null;
                    ManagementObject[] vhdList = WmiUtilities.GetVhdSettings(vm);
                    if (vhdList != null)
                    {
                        sasds = new string[vhdList.Length];

                        for (uint index = 0; index < vhdList.Length; ++index)
                        {
                            using (ManagementObject vhd = vhdList[index])
                            {
                                // Change the VHD path to an empty string, which will force
                                // the system to use resource pools to get the right path at
                                // the destination node.
                                vhd["HostResource"] = new string[] { "" };

                                // Create an array of embedded instances.
                                sasds[index] = vhd.GetText(TextFormat.CimDtd20);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No VHDs found associated with the VM. Skipping VHDs...");
                    }

                    // Perform migration.
                    Console.WriteLine("Performing migration...");
                    Migrate(srcScope,
                            vmName,
                            destinationHost,
                            migrationSettingData.GetText(TextFormat.CimDtd20),
                            null,
                            sasds);
                }
        }
Пример #4
0
        private void AddVirtualNetwork(string vmName, string nicName, string address)
        {
            if (string.IsNullOrEmpty(vmName))
            {
                throw new ArgumentNullException("vmName");
            }

            using (ManagementObject service = Utility.GetServiceObject(managementScope, "Msvm_VirtualSystemManagementService"))
                using (ManagementObject vm = Utility.GetTargetComputer(vmName, managementScope))
                    using (ManagementBaseObject inP = service.GetMethodParameters("AddVirtualSystemResources"))
                        using (ManagementObject nicDefault = Utility.GetResourceDataDefault(
                                   managementScope, ResourceType.EthernetAdapter, ResourceSubType.EthernetSynthetic, null))
                        {
                            if (address != null)
                            {
                                nicDefault["StaticMacAddress"] = true;
                                nicDefault["Address"]          = address;
                            }
                            else
                            {
                                nicDefault["StaticMacAddress"] = false;
                            }

                            nicDefault["ElementName"] = nicName;
                            var identifiers = new String[1];
                            identifiers[0] = string.Format(CultureInfo.InvariantCulture, "{{{0}}}", Guid.NewGuid());
                            nicDefault["VirtualSystemIdentifiers"] = identifiers;

                            var rasDs = new string[1];
                            rasDs[0] = nicDefault.GetText(TextFormat.CimDtd20);

                            inP["ResourcesettingData"] = rasDs;
                            inP["TargetSystem"]        = vm.Path.Path;

                            ManagementBaseObject outP = service.InvokeMethod("AddVirtualSystemResources", inP, null);
                            if (outP == null)
                            {
                                throw new ArgumentException("Could not add virtual network!");
                            }

                            if ((UInt32)outP["ReturnValue"] == ReturnCode.Started)
                            {
                                NewTask(outP, managementScope);
                            }

                            NewTask((UInt32)outP["ReturnValue"]);
                        }

            //ConnectSwitchPort connect = new ConnectSwitchPort(serverName);
            //connect.Connect(nicName, nicName + "_ExternalPort", vmName, "synthetic", null);
        }
Пример #5
0
        ConfigureMetricsFlushInterval(
            TimeSpan interval)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Create an instance of the Msvm_MetricServiceSettingData class and set the specified
            // metrics flush interval. Note that the TimeSpan must be converted to a DMTF time
            // interval first.
            //
            string dmtfTimeInterval = ManagementDateTimeConverter.ToDmtfTimeInterval(interval);

            string serviceSettingDataEmbedded;

            using (ManagementClass serviceSettingDataClass = new ManagementClass(
                       "Msvm_MetricServiceSettingData"))
            {
                serviceSettingDataClass.Scope = scope;

                using (ManagementObject serviceSettingData = serviceSettingDataClass.CreateInstance())
                {
                    serviceSettingData["MetricsFlushInterval"] = dmtfTimeInterval;

                    serviceSettingDataEmbedded = serviceSettingData.GetText(TextFormat.WmiDtd20);
                }
            }

            //
            // Call the Msvm_MetricService::ModifyServiceSettings method. Note that the
            // Msvm_MetricServiceSettingData instance must be passed as an embedded instance.
            //
            using (ManagementObject metricService = MetricUtilities.GetMetricService(scope))
            {
                using (ManagementBaseObject inParams =
                           metricService.GetMethodParameters("ModifyServiceSettings"))
                {
                    inParams["SettingData"] = serviceSettingDataEmbedded;

                    using (ManagementBaseObject outParams =
                               metricService.InvokeMethod("ModifyServiceSettings", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);

                        Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                        "The MetricsFlushInterval was successfully configured to interval \"{0}\".",
                                                        interval.ToString()));
                    }
                }
            }
        }
        AddAuthorizationEntry(
            string primaryHostSystem,
            string trustGroup,
            string replicaStoragePath)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Call the Msvm_ReplicationService::AddAuthorizationEntry method. Note that the
            // Msvm_ReplicationAuthorizationSettingData instance must be passed as an embedded instance.
            //
            using (ManagementObject replicationService =
                       ReplicaUtilities.GetVirtualMachineReplicationService(scope))
            {
                //
                // Create an instance of the Msvm_ReplicationAuthorizationSettingData.
                //
                string authSettingDataEmbedded;

                using (ManagementClass authSettingDataClass = new ManagementClass(
                           "Msvm_ReplicationAuthorizationSettingData"))
                {
                    authSettingDataClass.Scope = scope;

                    using (ManagementObject authSettingData = authSettingDataClass.CreateInstance())
                    {
                        authSettingData["AllowedPrimaryHostSystem"] = primaryHostSystem;
                        authSettingData["TrustGroup"]             = trustGroup;
                        authSettingData["ReplicaStorageLocation"] = replicaStoragePath;

                        authSettingDataEmbedded = authSettingData.GetText(TextFormat.WmiDtd20);

                        using (ManagementBaseObject inParams =
                                   replicationService.GetMethodParameters("AddAuthorizationEntry"))
                        {
                            inParams["AuthorizationEntry"] = authSettingDataEmbedded;

                            using (ManagementBaseObject outParams =
                                       replicationService.InvokeMethod("AddAuthorizationEntry", inParams, null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }

                            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                            "Replication is authorized for \"{0}\".", primaryHostSystem));
                        }
                    }
                }
            }
        }
Пример #7
0
        public static int ModifyDevice(this ManagementObject VM, ManagementObject Device, out ManagementObject Job)
        {
            Job = null;
            switch (VM["__CLASS"].ToString().ToUpperInvariant())
            {
            case "MSVM_COMPUTERSYSTEM":
                ManagementObject ServiceObj = GetServiceObject(VM.GetScope(), ServiceNames.VSManagement);
                Job = new ManagementObject();
                return((Int32)ServiceObj.InvokeMethod("ModifyVirtualSystemResources",
                                                      new object[] { VM.Path.Path, Device.GetText(TextFormat.WmiDtd20), null, Job }));

            default:
                return(-1);
            }
        }
        AddFeatureSettings(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string featureId = NetworkingUtilities.GetSwitchFeatureId(NetworkingUtilities.SwitchFeatureType.Bandwidth);

            using (ManagementObject managementService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))

                //
                // Find the specified switch.
                //
                using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                    using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                               ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                         "Msvm_SettingsDefineState",
                                                         null, null, null, null, false, null)))

                        //
                        // Add a new bandwidth setting instance.
                        //
                        using (ManagementObject bandwidthSetting =
                                   NetworkingUtilities.GetDefaultFeatureSetting(featureId, scope))
                        {
                            //
                            // Set the default bandwidth reservation to 10 Mbps.
                            //
                            bandwidthSetting["DefaultFlowReservation"] = 12500000; // in bytes/sec

                            using (ManagementBaseObject inParams =
                                       managementService.GetMethodParameters("AddFeatureSettings"))
                            {
                                inParams["AffectedConfiguration"] = ethernetSwitchSetting.Path.Path;
                                inParams["FeatureSettings"]       = new string[] { bandwidthSetting.GetText(TextFormat.WmiDtd20) };

                                using (ManagementBaseObject outParams =
                                           managementService.InvokeMethod("AddFeatureSettings", inParams, null))
                                {
                                    WmiUtilities.ValidateOutput(outParams, scope);
                                }
                            }
                        }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully added bandwidth feature setting to virtual switch '{0}'.",
                                            switchName));
        }
        ModifyFeatureSettings(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject managementService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))

                //
                // Find the specified switch.
                //
                using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                    using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                               ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                         "Msvm_SettingsDefineState",
                                                         null, null, null, null, false, null)))

                        //
                        // Find the existing bandwidth setting and modify it.
                        //
                        using (ManagementObject bandwidthSetting = WmiUtilities.GetFirstObjectFromCollection(
                                   ethernetSwitchSetting.GetRelated("Msvm_VirtualEthernetSwitchBandwidthSettingData",
                                                                    "Msvm_VirtualEthernetSwitchSettingDataComponent",
                                                                    null, null, null, null, false, null)))
                        {
                            //
                            // Increase the current reservation by 1 Mbps.
                            //
                            bandwidthSetting["DefaultFlowReservation"] =
                                (UInt64)bandwidthSetting["DefaultFlowReservation"] + 125000; // in bytes/sec

                            using (ManagementBaseObject inParams =
                                       managementService.GetMethodParameters("ModifyFeatureSettings"))
                            {
                                inParams["FeatureSettings"] = new string[] { bandwidthSetting.GetText(TextFormat.WmiDtd20) };

                                using (ManagementBaseObject outParams =
                                           managementService.InvokeMethod("ModifyFeatureSettings", inParams, null))
                                {
                                    WmiUtilities.ValidateOutput(outParams, scope);
                                }
                            }
                        }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully modified bandwidth feature setting on virtual switch '{0}'.",
                                            switchName));
        }
        CreateSwitch(
            string switchName,
            string switchNotes,
            string[] ports,
            ManagementScope scope)
        {
            string switchSettingText;

            //
            // Create the configuration object we pass into the CreateSwitch method in order to
            // specify details about the switch to create, such as its name and any notes.
            //
            using (ManagementClass switchSettingClass =
                       new ManagementClass("Msvm_VirtualEthernetSwitchSettingData"))
            {
                switchSettingClass.Scope = scope;
                using (ManagementObject switchSetting = switchSettingClass.CreateInstance())
                {
                    switchSetting["ElementName"] = switchName;
                    switchSetting["Notes"]       = new string[] { switchNotes };

                    //
                    // You can also configure other aspects of the switch before you create it,
                    // such as its IOVPreferred property.
                    //
                    // switchSetting["IOVPreferred"] = true;

                    switchSettingText = switchSetting.GetText(TextFormat.WmiDtd20);
                }
            }

            //
            // Now create the switch with the specified ports.
            //
            using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                using (ManagementBaseObject inParams = switchService.GetMethodParameters("DefineSystem"))
                {
                    inParams["SystemSettings"]   = switchSettingText;
                    inParams["ResourceSettings"] = ports;

                    using (ManagementBaseObject outParams =
                               switchService.InvokeMethod("DefineSystem", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }
        }
        ReverseReplicationRelationship(
            string name)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the Msvm_ComputerSystem.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
            {
                string vmPath = vm.Path.Path;

                using (ManagementObject replicationSettingData = ReplicaUtilities.GetReplicationSettings(vm))
                {
                    //
                    // Simply reverse the recovery server name with that of primary, other
                    // properties are already populated.
                    //
                    replicationSettingData["RecoveryConnectionPoint"] =
                        replicationSettingData["PrimaryConnectionPoint"];

                    string settingDataEmbedded = replicationSettingData.GetText(TextFormat.WmiDtd20);

                    using (ManagementObject replicationService =
                               ReplicaUtilities.GetVirtualMachineReplicationService(scope))
                    {
                        using (ManagementBaseObject inParams =
                                   replicationService.GetMethodParameters("ReverseReplicationRelationship"))
                        {
                            inParams["ComputerSystem"]         = vmPath;
                            inParams["ReplicationSettingData"] = settingDataEmbedded;

                            using (ManagementBaseObject outParams =
                                       replicationService.InvokeMethod("ReverseReplicationRelationship",
                                                                       inParams,
                                                                       null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                    }

                    Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                    "Replication is successfully reversed for virtual machine \"{0}\"", name));
                }
            }
        }
Пример #12
0
        internal static ManagementBaseObject AddResourceSettings(
            this ManagementScope scope,
            ManagementObject virtualSystemSettingData,
            ManagementObject resourceSettingData)
        {
            var virtualSystemManagementService = scope.GetVirtualSystemManagementService();

            var inParameters = virtualSystemManagementService.GetMethodParameters("AddResourceSettings");

            inParameters["AffectedConfiguration"] = virtualSystemSettingData;
            inParameters["ResourceSettings"]      = new string[]
            {
                resourceSettingData.GetText(TextFormat.WmiDtd20)
            };

            return(virtualSystemManagementService.InvokeMethod("AddResourceSettings", inParameters, null));
        }
        ConfigWwnGenerator(
            string minWwpn,
            string maxWwpn,
            string newWwnn)
        {
            Console.WriteLine("Trying to configure the WWN generator with:");
            Console.WriteLine("\tMinimumWWPNAddress = {0}", minWwpn);
            Console.WriteLine("\tMaximumWWPNAddress = {0}", maxWwpn);

            if (newWwnn == null)
            {
                Console.WriteLine("\tThe CurrentWWNNAddress will not be modified.");
            }
            else
            {
                Console.WriteLine("\tCurrentWWNNAddress = {0}", newWwnn);
            }

            ManagementScope scope = FibreChannelUtilities.GetFcScope();

            using (ManagementObject service =
                       WmiUtilities.GetVirtualMachineManagementService(scope))
                using (ManagementObject settings =
                           WmiUtilities.GetVirtualMachineManagementServiceSettings(scope))
                    using (ManagementBaseObject inParams =
                               service.GetMethodParameters("ModifyServiceSettings"))
                    {
                        settings["MinimumWWPNAddress"] = minWwpn;
                        settings["MaximumWWPNAddress"] = maxWwpn;
                        if (newWwnn != null)
                        {
                            settings["CurrentWWNNAddress"] = newWwnn;
                        }

                        inParams["SettingData"] = settings.GetText(TextFormat.WmiDtd20);
                        using (ManagementBaseObject outParams =
                                   service.InvokeMethod("ModifyServiceSettings",
                                                        inParams,
                                                        null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope, true, true);
                        }
                    }

            Console.WriteLine("Successfully configured the WWN Generator.");
        }
Пример #14
0
        public static VMJob SetVMResource(VM vm, ManagementObject resource, Dictionary <string, object> Params)
        {
            ManagementScope      scope = new ManagementScope(@"\\" + vm.Host.Name + @"\root\virtualization", vm.Host.HostConnectionOptions);
            ManagementObject     virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");
            ManagementBaseObject inParams             = virtualSystemService.GetMethodParameters("ModifyVirtualSystemResources");
            ManagementObject     vmObj = vm.Instance;

            //ManagementObject resource = GetMemory(vm);
            //memSettings["Limit"] = quantity;
            //memSettings["Reservation"] = quantity;
            foreach (string key in Params.Keys)
            {
                resource[key] = Params[key];
            }
            //resource["VirtualQuantity"] = quantity;
            string[] Resources = new string[1];
            Resources[0] = resource.GetText(TextFormat.CimDtd20);
            //ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ModifyVirtualSystemResources");
            inParams["ComputerSystem"]      = vmObj.Path.Path;
            inParams["ResourcesettingData"] = Resources;
            VMJob ThisJob = null;
            ManagementBaseObject outParams = virtualSystemService.InvokeMethod("ModifyVirtualSystemResources", inParams, null);
            //MessageBox.Show(outParams.GetText(TextFormat.Mof));
            string jobPath     = (string)outParams["Job"];
            UInt32 returnValue = (UInt32)outParams["ReturnValue"];

            if (jobPath != null)
            {
                ManagementObject jobObj = new ManagementObject(scope, new ManagementPath(jobPath), null);
                ThisJob = new VMJob(jobObj);
            }
            inParams.Dispose();
            //resource.Dispose();
            outParams.Dispose();
            vmObj.Dispose();

            virtualSystemService.Dispose();
            if ((jobPath == null) && (returnValue != ReturnCode.Completed) && (returnValue != ReturnCode.Started))
            {
                throw new VMResourcesUpdateException(returnValue);
            }
            return(ThisJob);
        }
Пример #15
0
        private static string GetVirtualSystemGlobalSettingDataInstance(ManagementScope scope, string machineName)
        {
            var settingPath = new ManagementPath("Msvm_VirtualSystemGlobalsettingData");

            using (var globalSettingClass = new ManagementClass(scope, settingPath, null))
            {
                using (ManagementObject globalSettingData = globalSettingClass.CreateInstance())
                {
                    if (globalSettingData == null)
                    {
                        throw new ArgumentException("Could not get global machine settings.");
                    }

                    globalSettingData["ElementName"] = machineName;

                    return(globalSettingData.GetText(TextFormat.CimDtd20));
                }
            }
        }
        ModifyServiceSettings(
            bool enableReplicaServer)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");
            string          serviceSettingDataEmbedded;

            //
            // Call the Msvm_ReplicationService::ModifyServiceSettings method. Note that the
            // Msvm_ReplicationServiceSettingData instance must be passed as an embedded instance.
            //
            using (ManagementObject replicationService =
                       ReplicaUtilities.GetVirtualMachineReplicationService(scope))
            {
                //
                // Gets an instance of the Msvm_ReplicationServiceSettingData class and set the
                // RecoveryServerEnabled field. Note that this sample enables the replication server
                // for integrated authentication.
                //
                using (ManagementObject serviceSettingData =
                           ReplicaUtilities.GetReplicationServiceSettings(replicationService))
                {
                    serviceSettingData["RecoveryServerEnabled"]     = enableReplicaServer;
                    serviceSettingData["AllowedAuthenticationType"] = 1;
                    serviceSettingDataEmbedded = serviceSettingData.GetText(TextFormat.WmiDtd20);

                    using (ManagementBaseObject inParams =
                               replicationService.GetMethodParameters("ModifyServiceSettings"))
                    {
                        inParams["SettingData"] = serviceSettingDataEmbedded;

                        using (ManagementBaseObject outParams =
                                   replicationService.InvokeMethod("ModifyServiceSettings", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }

                        Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                        "The replication service was successfully {0}.",
                                                        enableReplicaServer ? "enabled" : "disabled"));
                    }
                }
            }
        }
        SetAuthorizationEntry(
            string name,
            string primaryHostSystem)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the Msvm_ComputerSystem.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
            {
                string vmPath = vm.Path.Path;

                using (ManagementObject authEntry =
                           ReplicaUtilities.GetAuthorizationEntry(primaryHostSystem))
                {
                    string authEntryEmbedded = authEntry.GetText(TextFormat.WmiDtd20);

                    using (ManagementObject replicationService =
                               ReplicaUtilities.GetVirtualMachineReplicationService(scope))
                    {
                        using (ManagementBaseObject inParams =
                                   replicationService.GetMethodParameters("SetAuthorizationEntry"))
                        {
                            inParams["ComputerSystem"]     = vmPath;
                            inParams["AuthorizationEntry"] = authEntryEmbedded;

                            using (ManagementBaseObject outParams =
                                       replicationService.InvokeMethod("SetAuthorizationEntry",
                                                                       inParams,
                                                                       null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                    }

                    Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                    "Replication for virtual machine \"{0}\" is successfully associated with \"{1}\"",
                                                    name, primaryHostSystem));
                }
            }
        }
Пример #18
0
        public bool ExportVirtualSystem(VirtualMachine virtualMachine, SnapshotExport snapshotExport)
        {
            virtualMachine.ExportPercentComplete = 0;

            bool exportSuccess = true;
            var  scope         = WmiRoutines.GetScope(WmiRoutines.NAMESPACE_HYPER_V);

            using (ManagementObject virtualSystemService = WmiRoutines.GetServiceObject(scope, "Msvm_VirtualSystemManagementService"))
                using (ManagementObject srv = GetVirtualMachine(scope, virtualMachine.Name))
                    using (ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ExportSystemDefinition"))
                    {
                        if (!Directory.Exists(virtualMachine.ExportPath))
                        {
                            Directory.CreateDirectory(virtualMachine.ExportPath);
                        }

                        ManagementPath settingPath = new ManagementPath("Msvm_VirtualSystemExportSettingData");

                        using (ManagementClass exportSettingDataClass = new ManagementClass(scope, settingPath, null))
                            using (ManagementObject exportSettingData = exportSettingDataClass.CreateInstance())
                            {
                                exportSettingData["CopySnapshotConfiguration"]  = snapshotExport;
                                exportSettingData["CopyVmRuntimeInformation"]   = true;
                                exportSettingData["CopyVmStorage"]              = true;
                                exportSettingData["CreateVmExportSubdirectory"] = true;

                                string settingData = exportSettingData.GetText(TextFormat.CimDtd20);

                                inParams["ComputerSystem"]    = srv.Path.Path;
                                inParams["ExportDirectory"]   = virtualMachine.ExportPath;
                                inParams["ExportSettingData"] = settingData;
                            }

                        using (ManagementBaseObject outParams = virtualSystemService.InvokeMethod("ExportSystemDefinition",
                                                                                                  inParams, null))
                        {
                            exportSuccess = ValidateOutput(virtualMachine, outParams, scope, false, true);
                        }
                    }

            virtualMachine.ExportPercentComplete = 100;
            return(exportSuccess);
        }
Пример #19
0
        Enable(
            string serverName,
            bool set,
            bool enable)
        {
            ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

            using (ManagementObject settings = WmiUtilities.GetVirtualMachineManagementServiceSettings(scope))
                using (ManagementObject service = WmiUtilities.GetVirtualMachineManagementService(scope))
                {
                    if (set)
                    {
                        using (ManagementBaseObject inParams = service.GetMethodParameters("ModifyServiceSettings"))
                        {
                            settings["EnhancedSessionModeEnabled"] = enable;
                            inParams["SettingData"] = settings.GetText(TextFormat.WmiDtd20);

                            using (ManagementBaseObject outParams =
                                       service.InvokeMethod("ModifyServiceSettings",
                                                            inParams,
                                                            null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope, true, true);
                            }
                        }

                        Console.WriteLine("Successfully {0} enhanced session mode.", enable ? "enabled" : "disabled");
                        return;
                    }

                    bool enabled = (bool)settings["EnhancedSessionModeEnabled"];

                    if (enabled)
                    {
                        Console.WriteLine("Enhanced Session Mode is enabled");
                    }
                    else
                    {
                        Console.WriteLine("Enhanced Session Mode is disabled");
                    }
                }
        }
Пример #20
0
        SetGeneration2BootProtocol(
            string serverName,
            string vmName,
            UInt16 protocol)
        {
            ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
                using (ManagementObject vmSettings = WmiUtilities.GetVirtualMachineSettings(vm))
                {
                    string virtualSystemSubType = (string)vmSettings["VirtualSystemSubType"];

                    if (!string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:2", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("VM {0} on server {1} is not generation 2", vmName, serverName);
                        return;
                    }

                    //
                    // Modify the virtual system to use the new protocol.
                    //

                    vmSettings["NetworkBootPreferredProtocol"] = protocol;

                    using (ManagementObject service = WmiUtilities.GetVirtualMachineManagementService(scope))
                        using (ManagementBaseObject inParams = service.GetMethodParameters("ModifySystemSettings"))
                        {
                            inParams["SystemSettings"] = vmSettings.GetText(TextFormat.WmiDtd20);

                            using (ManagementBaseObject outParams =
                                       service.InvokeMethod("ModifySystemSettings",
                                                            inParams,
                                                            null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope, true, true);
                            }

                            Console.WriteLine("Successfully modified boot protocol");
                            return;
                        }
                }
        }
Пример #21
0
        public static void NewVM(string serverName, string vmName)
        {
            ManagementPath classPath = new ManagementPath()
            {
                Server        = serverName,
                NamespacePath = @"\root\virtualization\v2",
                ClassName     = "Msvm_VirtualSystemSettingData"
            };

            using (ManagementClass virtualSystemSettingClass = new ManagementClass(classPath))
            {
                Credentials.conOpts.Username       = Credentials.username;
                Credentials.conOpts.SecurePassword = Credentials.password;
                Credentials.conOpts.Authority      = Credentials.domain;
                Credentials.conOpts.Impersonation  = ImpersonationLevel.Impersonate;

                ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", Credentials.conOpts);

                virtualSystemSettingClass.Scope = scope;

                using (ManagementObject virtualSystemSetting = virtualSystemSettingClass.CreateInstance())
                {
                    virtualSystemSetting["ElementName"]          = vmName;
                    virtualSystemSetting["VirtualsystemSubtype"] = "Microsoft:Hyper-V:Subtype:2";

                    string embeddedInstance = virtualSystemSetting.GetText(TextFormat.WmiDtd20);

                    using (ManagementObject service = Functions.getVMManagementService(scope))
                        using (ManagementBaseObject inParams = service.GetMethodParameters("DefineSystem"))
                        {
                            inParams["SystemSettings"] = embeddedInstance;

                            using (ManagementBaseObject outParams = service.InvokeMethod("DefineSystem", inParams, null))
                            {
                                Console.WriteLine("ret={0}", outParams["ReturnValue"]);
                            }
                        }
                }
            }
        }
Пример #22
0
        public static ManagementObject AddDevice(this ManagementObject VM, ManagementObject Device)
        {
            switch (VM["__CLASS"].ToString().ToUpperInvariant())
            {
            case "MSVM_COMPUTERSYSTEM":
                ManagementObject     ServiceObj = GetServiceObject(VM.GetScope(), ServiceNames.VSManagement);
                ManagementBaseObject inputs     = ServiceObj.GetMethodParameters("AddVirtualSystemResources");
                inputs["TargetSystem"]        = VM.Path.Path;
                inputs["ResourceSettingData"] = new string[] { Device.GetText(TextFormat.WmiDtd20) };
                var result = ServiceObj.InvokeMethod("AddVirtualSystemResources", inputs, null);
                switch (Int32.Parse(result["ReturnValue"].ToString()))
                {
                case (int)ReturnCodes.OK:
                    var tmp = result["NewResources"];
                    return(GetObject(((string[])result["NewResources"]).First()));

                case (int)ReturnCodes.JobStarted:
                    var job = GetObject(result["Job"].ToString());
                    var r   = WaitForJob(job);
                    if (r == 0)
                    {
                        var res  = result["NewResources"];
                        var arr  = (string[])res;
                        var path = arr.First();
                        var o    = GetObject(path);
                        return(GetObject(((string[])result["NewResources"]).First()));
                    }
                    var jobres = job.InvokeMethod("GetError", new ManagementObject(), null);
                    var errStr = jobres["Error"].ToString();
                    var errObj = GetObject(errStr);
                    return(null);

                default:
                    return(null);
                }

            default:
                return(null);
            }
        }
        SetGeneration2SecureBoot(
            string serverName,
            string vmName,
            bool val)
        {
            ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
            {
                using (ManagementObject vmSettings = WmiUtilities.GetVirtualMachineSettings(vm))
                {
                    string virtualSystemSubType = (string)vmSettings["VirtualSystemSubType"];

                    if (!string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:2", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("VM {0} on server {1} is not generation 2", vmName, serverName);
                        return;
                    }

                    vmSettings["SecureBootEnabled"] = val;

                    using (ManagementObject service = WmiUtilities.GetVirtualMachineManagementService(scope))
                        using (ManagementBaseObject inParams = service.GetMethodParameters("ModifySystemSettings"))
                        {
                            inParams["SystemSettings"] = vmSettings.GetText(TextFormat.WmiDtd20);

                            using (ManagementBaseObject outParams =
                                       service.InvokeMethod("ModifySystemSettings",
                                                            inParams,
                                                            null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope, true, true);
                            }

                            Console.WriteLine("Successfully set secure boot property.");
                            return;
                        }
                }
            }
        }
        CreateGeneration2VM(
            string serverName,
            string vmName)
        {
            ManagementPath classPath = new ManagementPath()
            {
                Server        = serverName,
                NamespacePath = @"\root\virtualization\v2",
                ClassName     = "Msvm_VirtualSystemSettingData"
            };

            using (ManagementClass virtualSystemSettingClass = new ManagementClass(classPath))
            {
                ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

                virtualSystemSettingClass.Scope = scope;

                using (ManagementObject virtualSystemSetting = virtualSystemSettingClass.CreateInstance())
                {
                    virtualSystemSetting["ElementName"]           = vmName;
                    virtualSystemSetting["ConfigurationDataRoot"] = "C:\\ProgramData\\Microsoft\\Windows\\Hyper-V\\";
                    virtualSystemSetting["VirtualSystemSubtype"]  = "Microsoft:Hyper-V:SubType:2";

                    string embeddedInstance = virtualSystemSetting.GetText(TextFormat.WmiDtd20);

                    // Get the management service, VM object and its settings.
                    using (ManagementObject service = WmiUtilities.GetVirtualMachineManagementService(scope))
                        using (ManagementBaseObject inParams = service.GetMethodParameters("DefineSystem"))
                        {
                            inParams["SystemSettings"] = embeddedInstance;

                            using (ManagementBaseObject outParams = service.InvokeMethod("DefineSystem", inParams, null))
                            {
                                Console.WriteLine("ret={0}", outParams["ReturnValue"]);
                            }
                        }
                }
            }
        }
        CreateExternalOnlySwitch(
            string externalAdapterName,
            string switchName,
            string switchNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string[] ports;

            //
            // Get the external adapter we are connecting to.
            //
            using (ManagementObject externalAdapter =
                       NetworkingUtilities.FindExternalAdapter(externalAdapterName, scope))

                //
                // Get the default Msvm_EthernetPortAllocationSettingData instance that we can use to
                // configure our external port connection for the switch.
                // Use the same switch name, appended with "_External", for the port name.
                // You can use any port name that you like.
                //
                using (ManagementObject portToCreate =
                           NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                {
                    portToCreate["ElementName"]  = switchName + "_External";
                    portToCreate["HostResource"] = new string[] { externalAdapter.Path.Path };

                    //
                    // Now create the switch with the external port.
                    //
                    ports = new string[] { portToCreate.GetText(TextFormat.WmiDtd20) };
                }

            CreateSwitch(switchName, switchNotes, ports, scope);

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The external-only switch '{0}' was created successfully.", switchName));
        }
        CreateInternalSwitch(
            string switchName,
            string switchNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string[] ports;

            //
            // Get the hosting computer system. When connecting an internal port, we specify the
            // path to the hosting computer system as what the port should connect to.
            //
            using (ManagementObject hostComputerSystem = WmiUtilities.GetHostComputerSystem(scope))

                //
                // Get the default Msvm_EthernetPortAllocationSettingData instance that we can use to
                // configure our internal port connection for the switch.
                // Use the same switch name, appended with "_Internal", for the port name.
                // You can use any port name that you like.
                //
                using (ManagementObject portToCreate =
                           NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                {
                    portToCreate["ElementName"]  = switchName + "_Internal";
                    portToCreate["HostResource"] = new string[] { hostComputerSystem.Path.Path };

                    //
                    // Now create the switch with the internal port.
                    //
                    ports = new string[] { portToCreate.GetText(TextFormat.WmiDtd20) };
                }

            CreateSwitch(switchName, switchNotes, ports, scope);

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The internal switch '{0}' was created successfully.", switchName));
        }
        EnableCompression(
            string sourceHost
            )
        {
            //
            // Get the service & service setting values.
            //

            ManagementScope scope = new ManagementScope(
                @"\\" + sourceHost + @"\root\virtualization\v2", null);

            using (ManagementObject service = GetVirtualMachineMigrationService(scope))
                using (ManagementObject serviceSettings = GetMigrationServiceSettings(service))
                {
                    Console.WriteLine("Is compression enabled: {0}",
                                      serviceSettings["EnableCompression"]);

                    //
                    // Set new setting values.
                    //

                    serviceSettings["EnableCompression"] = true;

                    // Perform service setting change.
                    using (ManagementBaseObject inParams = service.GetMethodParameters("ModifyServiceSettings"))
                    {
                        inParams["ServiceSettingData"] = serviceSettings.GetText(TextFormat.CimDtd20);

                        using (ManagementBaseObject outParams =
                                   service.InvokeMethod("ModifyServiceSettings", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }
                }
        }
Пример #28
0
        public static void newVhd(string serverName, string diskType, string diskFormat, string path, string parentPath, int maxInternalSize, int blockSize, int logicalSectorSize, int physicalSectorSize)
        {
            ManagementPath classPath = new ManagementPath()
            {
                Server        = serverName,
                NamespacePath = @"\root\virtualization\v2",
                ClassName     = "Msvm_VirtualHardDiskSettingData"
            };

            using (ManagementClass settingsClass = new ManagementClass(classPath))
            {
                Credentials.conOpts.Username       = Credentials.username;
                Credentials.conOpts.SecurePassword = Credentials.password;
                Credentials.conOpts.Authority      = Credentials.domain;
                Credentials.conOpts.Impersonation  = ImpersonationLevel.Impersonate;

                ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", Credentials.conOpts);

                settingsClass.Scope = scope;
                using (ManagementObject settingsInstance = settingsClass.CreateInstance())
                {
                    settingsInstance["Type"]               = diskType;
                    settingsInstance["Format"]             = diskFormat;
                    settingsInstance["Path"]               = path;
                    settingsInstance["ParentPath"]         = parentPath;
                    settingsInstance["MaxInternalSize"]    = maxInternalSize;
                    settingsInstance["BlockSize"]          = blockSize;
                    settingsInstance["LogicalSectorSize"]  = logicalSectorSize;
                    settingsInstance["PhysicalSectorSize"] = physicalSectorSize;

                    string settingsInstanceString = settingsInstance.GetText(TextFormat.WmiDtd20);

                    // return settingsInstanceString;
                }
            }
        }
        VmMigrationOverSmb(
            string sourceHost,
            string destinationHost,
            string vmName
            )
        {
            ManagementScope srcScope = new ManagementScope(
                @"\\" + sourceHost + @"\root\virtualization\v2", null);

            using (ManagementObject migrationSettingData = GetMigrationSettingData(srcScope))
            {
                migrationSettingData["MigrationType"] = MigrationType.VirtualSystem;
                migrationSettingData["TransportType"] = TransportType.SMB;

                // Perform migration.
                Console.WriteLine("Performing migration...");
                Migrate(srcScope,
                        vmName,
                        destinationHost,
                        migrationSettingData.GetText(TextFormat.CimDtd20),
                        null,
                        null);
            }
        }
        AddPorts(
            string switchName,
            string externalAdapterName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            string ethernetSwitchSettingPath;
            string portToCreateText;

            ObjectQuery externalAdapterQuery = new ObjectQuery(string.Format(CultureInfo.InvariantCulture,
                                                                             "select * from Msvm_ExternalEthernetPort where Name=\"{0}\"", externalAdapterName));

            //
            // When modifying the switch, we need to pass in its configuration object.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
                using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                {
                    ethernetSwitchSettingPath = ethernetSwitchSetting.Path.Path;
                }

            //
            // Get the external adapter that we want to add a connection to.
            //
            using (ManagementObjectSearcher externalAdapterExecute =
                       new ManagementObjectSearcher(scope, externalAdapterQuery))
                using (ManagementObjectCollection externalAdapterCollection = externalAdapterExecute.Get())
                {
                    if (externalAdapterCollection.Count == 0)
                    {
                        throw new ManagementException(string.Format(CultureInfo.InvariantCulture,
                                                                    "There is no external adapter with the name {0}.",
                                                                    externalAdapterName));
                    }

                    using (ManagementObject externalAdapter =
                               WmiUtilities.GetFirstObjectFromCollection(externalAdapterCollection))

                        //
                        // Get the default Msvm_EthernetPortAllocationSettingData instance, which we can use to
                        // configure our external port connection for the switch.
                        // Use the same switch name, appended with "_External", for the port name.
                        // You can use any port name that you like.
                        //
                        using (ManagementObject portToCreate =
                                   NetworkingUtilities.GetDefaultEthernetPortAllocationSettingData(scope))
                        {
                            portToCreate["ElementName"]  = switchName + "_External";
                            portToCreate["HostResource"] = new string[] { externalAdapter.Path.Path };

                            portToCreateText = portToCreate.GetText(TextFormat.WmiDtd20);
                        }
                }

            //
            // Now add the port connection to the switch.
            //
            using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                using (ManagementBaseObject inParams =
                           switchService.GetMethodParameters("AddResourceSettings"))
                {
                    inParams["AffectedConfiguration"] = ethernetSwitchSettingPath;
                    inParams["ResourceSettings"]      = new string[] { portToCreateText };

                    using (ManagementBaseObject outParams =
                               switchService.InvokeMethod("AddResourceSettings", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "We added an external port connection to '{0}' on the switch '{1}'.",
                                            externalAdapterName, switchName));
        }