EnumerateMetricsForResourcePool(
            string resourceType,
            string resourceSubType,
            string poolId)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the resource pool that we want to get metrics for and iterate through the
            // metric definitions that are supported by it.
            //
            using (ManagementObject pool =
                       WmiUtilities.GetResourcePool(resourceType, resourceSubType, poolId, scope))
                using (ManagementObjectCollection metricDefinitionCollection =
                           pool.GetRelated("Msvm_AggregationMetricDefinition",
                                           "Msvm_MetricDefForME",
                                           null, null, null, null, false, null))
                    using (ManagementObjectCollection metricValueCollection =
                               pool.GetRelated("Msvm_AggregationMetricValue",
                                               "Msvm_MetricForME",
                                               null, null, null, null, false, null))
                    {
                        foreach (ManagementObject metricDefinition in metricDefinitionCollection)
                        {
                            using (metricDefinition)
                            {
                                Console.WriteLine("Metric Definition:\t{0}", metricDefinition["ElementName"]);

                                //
                                // For each supported metric definition, retrieve the corresponding metric value.
                                //
                                string id = metricDefinition["Id"].ToString();

                                foreach (ManagementObject metricValue in metricValueCollection)
                                {
                                    using (metricValue)
                                    {
                                        string metricDefinitionId = metricValue["MetricDefinitionId"].ToString();

                                        if (metricDefinitionId == id)
                                        {
                                            Console.WriteLine("Metric Value:\t\t{0}", metricValue["MetricValue"]);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
        }
        public PerformanceSetting GetPerformanceSetting()
        {
            try
            {
                ManagementObjectCollection virtualSystemSettings = virtualMachine.GetRelated("Msvm_SummaryInformation");
                ManagementObject           virtualSystemSetting  = WmiUtilities.GetFirstObjectFromCollection(virtualSystemSettings);

                //Msvm_SummaryInformation
                performanceSetting.Name               = virtualSystemSetting.GetPropertyValue("Name") + "";
                performanceSetting.ElementName        = virtualSystemSetting.GetPropertyValue("ElementName") + "";
                performanceSetting.InstanceID         = virtualSystemSetting.GetPropertyValue("InstanceID") + "";
                performanceSetting.NumberOfProcessors = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("NumberOfProcessors"));
                performanceSetting.EnabledState       = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("EnabledState"));
                performanceSetting.HealthState        = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("HealthState"));
                performanceSetting.ProcessorLoad      = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("ProcessorLoad"));

                UInt16[] ProcessorHistoryInfo = (UInt16[])virtualSystemSetting.GetPropertyValue("ProcessorLoadHistory");
                performanceSetting.ProcessorLoadHistory = ProcessorHistoryInfo;

                performanceSetting.MemoryUsage          = Convert.ToUInt64(virtualSystemSetting.GetPropertyValue("MemoryUsage"));
                performanceSetting.GuestOperatingSystem = virtualSystemSetting.GetPropertyValue("GuestOperatingSystem") + "";
                //performanceSetting.AvailableMemoryBuffer = Convert.ToInt32(virtualSystemSetting.GetPropertyValue("AvailableMemoryBuffer"));

                using (ManagementObject detailVMSetting = WmiUtilities.GetVirtualMachineSettings(virtualMachine))
                {
                    using (ManagementObjectCollection processorSettingDatas = detailVMSetting.GetRelated("Msvm_ProcessorSettingData"))
                        using (ManagementObject processorSettingData = WmiUtilities.GetFirstObjectFromCollection(processorSettingDatas))
                        {
                            performanceSetting.CPU_Reservation = Convert.ToUInt64(processorSettingData.GetPropertyValue("Reservation"));
                            performanceSetting.CPU_Limit       = Convert.ToUInt64(processorSettingData.GetPropertyValue("Limit"));
                            performanceSetting.CPU_Weight      = Convert.ToUInt32(processorSettingData.GetPropertyValue("Weight"));
                        }
                    using (ManagementObjectCollection memorySettingDatas = detailVMSetting.GetRelated("Msvm_MemorySettingData"))
                        using (ManagementObject memorySettingData = WmiUtilities.GetFirstObjectFromCollection(memorySettingDatas))
                        {
                            performanceSetting.RAM_VirtualQuantity      = Convert.ToUInt64(memorySettingData.GetPropertyValue("VirtualQuantity"));
                            performanceSetting.RAM_Weight               = Convert.ToUInt32(memorySettingData.GetPropertyValue("Weight"));
                            performanceSetting.RAM_DynamicMemoryEnabled = Convert.ToBoolean(memorySettingData.GetPropertyValue("DynamicMemoryEnabled"));
                        }
                }

                performanceSetting.GuestCpuRatio = (((float)performanceSetting.CPU_Limit / 100000) * performanceSetting.NumberOfProcessors);
                performanceSetting.GuestCpuRatio = performanceSetting.GuestCpuRatio / 8;
                return(performanceSetting);
            }
            catch (Exception exp)
            {
                return(performanceSetting);
            }
        }
        ListRecoverySnapshots(
            string hostMachine,
            string vmName
            )
        {
            ManagementScope scope = new ManagementScope(
                @"\\" + hostMachine + @"\root\virtualization\v2", null);

            // Get the VM object and snapshot settings.
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
                using (ManagementObjectCollection settingsCollection =
                           vm.GetRelated("Msvm_VirtualSystemSettingData", "Msvm_SnapshotOfVirtualSystem",
                                         null, null, null, null, false, null))
                {
                    foreach (ManagementObject setting in settingsCollection)
                    {
                        using (setting)
                        {
                            string systemType = (string)setting["VirtualSystemType"];

                            if (string.Compare(systemType, VirtualSystemTypeNames.RecoverySnapshot,
                                               StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                // It is a recovery snapshot.
                                DateTime time = ManagementDateTimeConverter.ToDateTime(setting["CreationTime"].ToString());
                                Console.WriteLine("Recovery snapshot creation time: {0}", time);
                            }
                        }
                    }
                }
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the  snapshot that is the parent to the virtual system current settings
        /// </summary>
        /// <param name="vm">Virtual system instance</param>
        /// <returns></returns>
        public static ManagementObject GetLastAppliedVirtualSystemSnapshot(ManagementObject vm)
        {
            EnumerationOptions EnumOpts = new EnumerationOptions();

            EnumOpts.ReturnImmediately = false;
            ManagementObjectCollection settings = vm.GetRelated(
                "Msvm_VirtualSystemsettingData",
                "Msvm_PreviousSettingData",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                EnumOpts);
            ManagementObject virtualSystemsetting = null;

            if (settings != null)
            {
                foreach (ManagementObject setting in settings)
                {
                    virtualSystemsetting = setting;
                }
            }
            return(virtualSystemsetting);
        }
Esempio n. 5
0
        private static ManagementObject GetVirtualSwitchPort(ManagementObject virtualSwitch, string switchPortName)
        {
            if (virtualSwitch == null)
            {
                throw new ArgumentNullException("virtualSwitch");
            }
            if (switchPortName == null)
            {
                throw new ArgumentNullException("switchPortName");
            }
            ManagementObjectCollection switchPorts = virtualSwitch.GetRelated(
                "Msvm_SwitchPort",
                "Msvm_HostedAccessPoint",
                null,
                null,
                "Dependent",
                "Antecedent",
                false,
                null);

            ManagementObject switchPort = null;

            foreach (ManagementObject instance in switchPorts)
            {
                if (instance["ElementName"].ToString().ToLowerInvariant() == switchPortName.ToLowerInvariant())
                {
                    switchPort = instance;
                    break;
                }
            }

            return(switchPort);
        }
Esempio n. 6
0
        private ManagementObject GetVmEthernetPort(string vmName, string vmEthernetPortClass)
        {
            if (vmName == null)
            {
                throw new ArgumentNullException("vmName");
            }
            if (vmEthernetPortClass == null)
            {
                throw new ArgumentNullException("vmEthernetPortClass");
            }
            ManagementObject vmEthernetPort = null;
            ManagementObject computerSystem = Utility.GetTargetComputer(vmName, scope);

            ManagementObjectCollection vmEthernetPorts = computerSystem.GetRelated(
                vmEthernetPortClass,
                "Msvm_SystemDevice",
                null,
                null,
                "PartComponent",
                "GroupComponent",
                false,
                null);

            foreach (ManagementObject instance in vmEthernetPorts)
            {
                vmEthernetPort = instance;
                break;
            }

            return(vmEthernetPort);
        }
Esempio n. 7
0
        public static ManagementObject GetVirtualSystemSettingData(ManagementObject vm)
        {
            ManagementObject           vmSetting  = null;
            ManagementObjectCollection vmSettings = vm.GetRelated
                                                    (
                "Msvm_VirtualSystemSettingData",
                "Msvm_SettingsDefineState",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null
                                                    );

            if (vmSettings.Count != 1)
            {
                throw new Exception(String.Format("{0} instance of Msvm_VirtualSystemSettingData was found", vmSettings.Count));
            }

            foreach (ManagementObject instance in vmSettings)
            {
                vmSetting = instance;
                break;
            }

            return(vmSetting);
        }
Esempio n. 8
0
        ManagementObject GetVirtualSystemSetting(string vmName)
        {
            if (scope == null)
            {
                scope = getRemoteScope();
            }
            virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementObject virtualSystem = Utility.GetTargetComputer(vmName, scope);

            ManagementObjectCollection virtualSystemSettings = virtualSystem.GetRelated
                                                               (
                "Msvm_VirtualSystemSettingData",
                "Msvm_SettingsDefineState",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null
                                                               );

            ManagementObject virtualSystemSetting = null;

            foreach (ManagementObject instance in virtualSystemSettings)
            {
                virtualSystemSetting = instance;
                break;
            }

            return(virtualSystemSetting);
        }
        GetReplicationRelationshipObject(
            ManagementObject virtualMachine,
            UInt16 relationshipType)
        {
            if (relationshipType > 1)
            {
                throw new ArgumentException("Replication relationship should be either 0 or 1");
            }

            using (ManagementObjectCollection relationshipCollection =
                       virtualMachine.GetRelated("Msvm_ReplicationRelationship"))
            {
                if (relationshipCollection.Count == 0)
                {
                    throw new ManagementException(
                              "No Msvm_ReplicationRelationship instance could be found");
                }

                //
                // Return the relationship instance whose InstanceID ends with given relationship type.
                //
                foreach (ManagementObject relationshipObject in relationshipCollection)
                {
                    string instanceID = relationshipObject.GetPropertyValue("InstanceID").ToString();
                    if (instanceID.EndsWith(relationshipType.ToString(CultureInfo.CurrentCulture), StringComparison.CurrentCulture))
                    {
                        return(relationshipObject);
                    }
                }
            }

            return(null);
        }
Esempio n. 10
0
        private ManagementObject GetSnapshotByUniqueName(ManagementObject vm, string snapshotName)
        {
            ManagementObjectCollection settings = vm.GetRelated(
                "Msvm_VirtualSystemsettingData",
                null,
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null);

            foreach (ManagementObject item in settings)
            {
                // the 5 is a bit of a magic number, it is the ID of a  VirtualSystemSnapshot
                if ((ushort)item.Properties["SettingType"].Value == 5 &&
                    item.Properties["ElementName"].Value.ToString().StartsWith(snapshotName, StringComparison.CurrentCultureIgnoreCase))
                {
                    this.LogBuildMessage(string.Format(CultureInfo.InvariantCulture, "Getting named snapshot from server {0} of name [{1}]", item.Path.Path, item["ElementName"]));

                    return(item);
                }
            }

            return(null);
        }
Esempio n. 11
0
        public void ListRecoverySnapshots()
        {
            ManagementScope scope = AsRawMachine.Scope;

            // Get the VM object and snapshot settings.
            using (ManagementObject vm = Utility.GetTargetComputer(Name, scope))
                using (ManagementObjectCollection settingsCollection =
                           vm.GetRelated("Msvm_VirtualSystemSettingData", "Msvm_SnapshotOfVirtualSystem",
                                         null, null, null, null, false, null))
                {
                    foreach (ManagementObject setting in settingsCollection)
                    {
                        using (setting)
                        {
                            string systemType = (string)setting["VirtualSystemType"];

                            if (string.Compare(systemType, VirtualSystemTypeNames.RealizedSnapshot,
                                               StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                // It is a recovery snapshot.
                                DateTime time = ManagementDateTimeConverter.ToDateTime(setting["CreationTime"].ToString());
                                Console.WriteLine("Name: {0}\nRecovery snapshot creation time: {1}\n", (string)setting["ElementName"], time);
                            }
                        }
                    }
                }
        }
        EnumerateDiscreteMetricsForVm(
            string name)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the first aggregate metric associated with this virtual machine.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
                using (ManagementObjectCollection vmMetricCollection =
                           vm.GetRelated("Msvm_AggregationMetricValue",
                                         "Msvm_MetricForME",
                                         null, null, null, null, false, null))
                    using (ManagementObject vmAggregateMetric =
                               WmiUtilities.GetFirstObjectFromCollection(vmMetricCollection))
                    {
                        //
                        // Enumerate the discrete metrics that compose that aggregate metric.
                        //
                        using (ManagementObjectCollection discreteMetricCollection = vmAggregateMetric.GetRelated(
                                   null, "Msvm_MetricCollectionDependency", null, null, null, null, false, null))
                        {
                            foreach (ManagementObject discreteMetric in discreteMetricCollection)
                            {
                                using (discreteMetric)
                                {
                                    Console.WriteLine(
                                        "Discrete Metric Value:\t{0}", discreteMetric["MetricValue"]);
                                }
                            }
                        }
                    }
        }
Esempio n. 13
0
        GetImportedPvm(
            ManagementBaseObject outputParameters)
        {
            ManagementObject pvm   = null;
            ManagementScope  scope = new ManagementScope(@"root\virtualization\v2");

            if (WmiUtilities.ValidateOutput(outputParameters, scope))
            {
                if ((uint)outputParameters["ReturnValue"] == 0)
                {
                    pvm = new ManagementObject((string)outputParameters["ImportedSystem"]);
                }

                if ((uint)outputParameters["ReturnValue"] == 4096)
                {
                    using (ManagementObject job =
                               new ManagementObject((string)outputParameters["Job"]))
                        using (ManagementObjectCollection pvmCollection =
                                   job.GetRelated("Msvm_PlannedComputerSystem",
                                                  "Msvm_AffectedJobElement", null, null, null, null, false, null))
                        {
                            pvm = WmiUtilities.GetFirstObjectFromCollection(pvmCollection);
                        }
                }
            }

            return(pvm);
        }
        /// <summary>
        /// Returns the specified Msvm_ResourceAllocationSettingData MOB.
        /// </summary>
        /// <remarks>Role/Range: 0/0 - Default; 3/1 Minimum; 3/2 Maximum; 3/3 Incremental</remarks>
        /// <param name="scope">The ManagementScope to use to connect to WMI.</param>
        /// <param name="pool">Mvm_ResourcePool MOB.</param name>
        /// <param name="valueRole"MvmCim_SettingsDefineCapabilities_ResourcePool ValueRole property.</param name>
        /// <param name="valueRange"MvmCim_SettingsDefineCapabilities_ResourcePool ValueRange property.</param name>
        /// <returns>Msvm_ResourceAllocationSettingData MOB.</returns>
        internal static ManagementObject GetPrototypeAllocationSettings(
            ManagementScope scope,
            ManagementObject pool,
            string valueRole,
            string valueRange)
        {
            foreach (ManagementObject allocationCapability in pool.GetRelated("Msvm_AllocationCapabilities",
                                                                              "Msvm_ElementCapabilities",
                                                                              null, null, null, null, false, null))
            {
                using (allocationCapability)
                {
                    foreach (ManagementObject relationship in allocationCapability.GetRelationships("Cim_SettingsDefineCapabilities"))
                    {
                        using (relationship)
                        {
                            if (relationship["ValueRole"].ToString() == valueRole &&
                                relationship["ValueRange"].ToString() == valueRange)
                            {
                                ManagementObject rasd = new ManagementObject(
                                    pool.Scope,
                                    new ManagementPath(relationship["PartComponent"].ToString()),
                                    null);

                                return(rasd);
                            }
                        }
                    }
                }
            }

            return(null);
        }
        GetResourcesToRemove(
            ManagementObject managementService,
            ManagementObject virtualMachine,
            WorldWideName wwnA,
            WorldWideName wwnB)
        {
            using (ManagementObject virtualMachineSettings =
                       WmiUtilities.GetVirtualMachineSettings(virtualMachine))
            {
                ManagementObjectCollection fcPortCollection = virtualMachineSettings.GetRelated(
                    "Msvm_SyntheticFcPortSettingData",
                    "Msvm_VirtualSystemSettingDataComponent",
                    null, null, null, null, false, null);

                List <string> portsToRemove = new List <string>();
                foreach (ManagementObject fcPort in fcPortCollection)
                {
                    string primaryWwpn   = fcPort["VirtualPortWWPN"].ToString();
                    string primaryWwnn   = fcPort["VirtualPortWWNN"].ToString();
                    string secondaryWwpn = fcPort["SecondaryWWPN"].ToString();
                    string secondaryWwnn = fcPort["SecondaryWWNN"].ToString();

                    if (string.Equals(primaryWwpn, wwnA.PortName, StringComparison.OrdinalIgnoreCase) &&
                        string.Equals(primaryWwnn, wwnA.NodeName, StringComparison.OrdinalIgnoreCase) &&
                        string.Equals(secondaryWwpn, wwnB.PortName, StringComparison.OrdinalIgnoreCase) &&
                        string.Equals(secondaryWwnn, wwnB.NodeName, StringComparison.OrdinalIgnoreCase))
                    {
                        portsToRemove.Add(fcPort.Path.Path);
                    }
                }
                return(portsToRemove.ToArray());
            }
        }
Esempio n. 16
0
        private List <Device> GetListDevices()
        {
            var serialQuery = new SelectQuery("SELECT * FROM Win32_PnPEntity");
            var searcher    = new ManagementObjectSearcher(new ManagementScope(), serialQuery);

            var devices     = searcher.Get();
            var devicesList = new List <Device>();

            foreach (var fDevice in devices)
            {
                if (fDevice["PNPClass"] == null)
                {
                    continue;
                }
                ManagementObject device = (ManagementObject)fDevice;

                var driver = device.GetRelated("Win32_SystemDriver");


                if (driver.Count != 0)
                {
                    devicesList.Add(new Device(device, driver.OfType <ManagementObject>().FirstOrDefault()));
                    continue;
                }
                devicesList.Add(new Device(device, null));
            }

            return(devicesList);
        }
Esempio n. 17
0
        /// <summary>
        /// This method checks if the context user, belongs to the local administrators group
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>

        public bool CheckAdminRights(string username)
        {
            bool          result = false;
            List <string> admins = new List <string>();
            //SelectQuery query = new SelectQuery("Select AccountType from Win32_UserAccount where Name=\"" + username + "\"");
            SelectQuery query = new SelectQuery("SELECT * FROM win32_group WHERE Name=\"" + getAdministratorGroupName() + "\"");
            ManagementObjectSearcher   searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection OC       = searcher.Get();
            IEnumerator enumerator = OC.GetEnumerator();

            enumerator.MoveNext();
            ManagementObject           O          = (ManagementObject)enumerator.Current;
            ManagementObjectCollection adminusers = O.GetRelated("Win32_UserAccount");

            foreach (ManagementObject envVar in adminusers)
            {
                admins.Add(envVar["Name"].ToString());
                //Console.WriteLine("Username : {0}", envVar["Name"]);
                //foreach (PropertyData pd in envVar.Properties)
                //    Console.WriteLine(string.Format("  {0,20}: {1}", pd.Name, pd.Value));
            }
            if (admins.Contains(username))
            {
                result = true;
            }
            return(result);
        }
        GetGuestServiceInterfaceComponent(
            ManagementScope scope,
            string vmName)
        {
            ManagementObject guestServiceInterfaceComponent;

            using (ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(
                       vmName,
                       scope))
            {
                using (ManagementObjectCollection settingsCollection =
                           virtualMachine.GetRelated(
                               "Msvm_GuestServiceInterfaceComponent",
                               "Msvm_SystemDevice",
                               null,
                               null,
                               null,
                               null,
                               false,
                               null))
                {
                    guestServiceInterfaceComponent = WmiUtilities.GetFirstObjectFromCollection(
                        settingsCollection);
                }
            }

            return(guestServiceInterfaceComponent);
        }
Esempio n. 19
0
        public static void SetVmMemory(string serverName, string vmName, Int64 virtualQuantity)
        {
            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);
            ManagementObject virtualMachine = Functions.getVM(vmName, scope);
            ManagementObject memorySetting  = null;

            ManagementObject virtualMachineSettings = Functions.getVMSettingData(virtualMachine, scope);

            foreach (ManagementObject memorySettingData in virtualMachineSettings.GetRelated("Msvm_MemorySettingData"))
            {
                memorySetting = memorySettingData;
                break;
            }

            string[] resourceData = new string[1];
            memorySetting["VirtualQuantity"] = virtualQuantity;
            resourceData[0] = memorySetting.GetText(TextFormat.WmiDtd20);

            using (ManagementObject virtualSystem = Functions.getVMManagementService(scope))
                using (ManagementBaseObject inParams = virtualSystem.GetMethodParameters("ModifyResourceSettings"))
                {
                    inParams["ResourceSettings"] = resourceData;

                    using (ManagementBaseObject outParams = virtualSystem.InvokeMethod("ModifyResourceSettings", inParams, null))
                    {
                        Console.WriteLine("ret={0}", outParams["ReturnValue"]);
                    }
                }
        }
Esempio n. 20
0
        public static ManagementObject GetVirtualSystemSettingData(ManagementObject virtualMachine)
        {
            if (virtualMachine == null)
            {
                throw new ArgumentNullException("virtualMachine");
            }
            ManagementObject           vmSetting  = null;
            ManagementObjectCollection vmSettings = virtualMachine.GetRelated(
                "Msvm_VirtualSystemSettingData",
                "Msvm_SettingsDefineState",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null);

            if (vmSettings.Count != 1)
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture, "{0} instance of Msvm_VirtualSystemSettingData was found", vmSettings.Count));
            }

            foreach (ManagementObject instance in vmSettings)
            {
                vmSetting = instance;
                break;
            }

            return(vmSetting);
        }
Esempio n. 21
0
        public static ManagementObject GetSystemDevice
        (
            string deviceClassName,
            string deviceObjectElementName,
            string vmName,
            ManagementScope scope)
        {
            ManagementObject systemDevice   = null;
            ManagementObject computerSystem = Utility.GetTargetComputer(vmName, scope);

            ManagementObjectCollection systemDevices = computerSystem.GetRelated
                                                       (
                deviceClassName,
                "Msvm_SystemDevice",
                null,
                null,
                "PartComponent",
                "GroupComponent",
                false,
                null
                                                       );

            foreach (ManagementObject device in systemDevices)
            {
                if (device["ElementName"].ToString().ToLower() == deviceObjectElementName.ToLower())
                {
                    systemDevice = device;
                    break;
                }
            }

            return(systemDevice);
        }
Esempio n. 22
0
        public static ManagementObject GetSystemDevice(
            string deviceClassName,
            string deviceObjectElementName,
            string virtualMachineName,
            ManagementScope scope)
        {
            if (deviceObjectElementName == null)
            {
                throw new ArgumentNullException("deviceObjectElementName");
            }
            ManagementObject systemDevice   = null;
            ManagementObject computerSystem = GetTargetComputer(virtualMachineName, scope);

            ManagementObjectCollection systemDevices = computerSystem.GetRelated(
                deviceClassName,
                "Msvm_SystemDevice",
                null,
                null,
                "PartComponent",
                "GroupComponent",
                false,
                null);

            foreach (ManagementObject device in systemDevices)
            {
                if (device["ElementName"].ToString().ToUpperInvariant() == deviceObjectElementName.ToUpperInvariant())
                {
                    systemDevice = device;
                    break;
                }
            }

            return(systemDevice);
        }
Esempio n. 23
0
        private void PrintObject(ManagementScope scope, string path)
        {
            var    site = new ManagementObject(scope, new ManagementPath(path), null);
            object desc = site["Description"];

            foreach (var rel in site.GetRelationships())
            {
                Console.WriteLine("rel: " + rel);
            }
            foreach (var rel in site.GetRelated())
            {
                Console.WriteLine("related: " + rel);
            }

            Console.WriteLine("props:");
            foreach (var prop in site.Properties)
            {
                Console.WriteLine("  {0}: {1}", prop.Name, prop.Value);
            }
            Console.WriteLine("system props:");
            foreach (var prop in site.SystemProperties)
            {
                Console.WriteLine("  {0}: {1}", prop.Name, prop.Value);
            }
        }
Esempio n. 24
0
        private static ManagementObject[] getVHDSettings(ManagementObject mObject)
        {
            const UInt16 SASDResourceTypeLogicalDisk = 31;

            List <ManagementObject> StorageAllocationSettingData = new List <ManagementObject>();

            using (ManagementObjectCollection mCollection = mObject.GetRelated(wmiClass.Msvm_StorageAllocationSettingData.ToString(), wmiClass.Msvm_VirtualSystemSettingDataComponent.ToString(), null, null, null, null, false, null))
            {
                foreach (ManagementObject mReturn in mCollection)
                {
                    if ((UInt16)mReturn["ResourceType"] == SASDResourceTypeLogicalDisk)
                    {
                        StorageAllocationSettingData.Add(mReturn);
                    }
                    else
                    {
                        mReturn.Dispose();
                    }
                }
            }
            if (StorageAllocationSettingData.Count == 0)
            {
                return(null);
            }
            else
            {
                return(StorageAllocationSettingData.ToArray());
            }
        }
Esempio n. 25
0
        private static ManagementObject GetVmLanEndPoint(ManagementObject vmEthernetPort)
        {
            if (vmEthernetPort == null)
            {
                throw new ArgumentNullException("vmEthernetPort");
            }
            ManagementObjectCollection vmEndPoints = vmEthernetPort.GetRelated(
                "Msvm_VMLanEndPoint",
                "Msvm_DeviceSAPImplementation",
                null,
                null,
                "Dependent",
                "Antecedent",
                false,
                null);

            ManagementObject vmEndPoint = null;

            foreach (ManagementObject instance in vmEndPoints)
            {
                vmEndPoint = instance;
                break;
            }

            return(vmEndPoint);
        }
Esempio n. 26
0
        public static IDictionary <string, string> GetKvpItems(VM vm)
        {
            ManagementObject           vmObj        = vm.Instance;
            ManagementObjectCollection exchCompColl = vmObj.GetRelated("Msvm_KvpExchangeComponent");
            //string dnsName = null;
            Dictionary <string, string> kvpDict = new Dictionary <string, string>();

            foreach (ManagementObject exchComp in exchCompColl)
            {
                string[] kvpstrings = (string[])exchComp["GuestIntrinsicExchangeItems"];
                foreach (string kvpstring in kvpstrings)
                {
                    //kvpstring contains XML representation of Msvm_KvpExchangeDataItem object.
                    XElement xkvp = XElement.Parse(kvpstring);
                    kvpDict.Add(xkvp.Elements("PROPERTY").Single(p => p.Attribute("NAME").Value == "Name").Element("VALUE").Value, xkvp.Elements("PROPERTY").Single(p => p.Attribute("NAME").Value == "Data").Element("VALUE").Value);
                    //test if Name property of Msvm_KvpExchangeDataItem object is FullyQualifiedDomainName
                    //if (xkvp.Elements("PROPERTY").Any(p => p.Attribute("NAME").Value == "Name" && p.Element("VALUE").Value == "FullyQualifiedDomainName"))
                    //{
                    //    //get Fully Qualified DomainName from Value of Data property
                    //    dnsName = xkvp.Elements("PROPERTY").Single(p => p.Attribute("NAME").Value == "Data").Element("VALUE").Value;
                    //    break;
                    //}
                }
                break;
            }
            return(kvpDict);
        }
Esempio n. 27
0
        internal ManagementObject CreateResource(Resources resource)
        {
            string resourcePoolClass = "Msvm_ResourcePool";

            if (resource == Resources.Processor)
            {
                resourcePoolClass = "Msvm_ProcessorPool";
            }

            string resourceSubType = "";

            switch (resource)
            {
            case Resources.Processor: resourceSubType = "Microsoft:Hyper-V:Processor"; break;

            case Resources.Memory: resourceSubType = "Microsoft:Hyper-V:Memory"; break;

            case Resources.SCSIController: resourceSubType = "Microsoft:Hyper-V:Synthetic SCSI Controller"; break;

            case Resources.VirtualHardDrive: resourceSubType = "Microsoft:Hyper-V:Synthetic Disk Drive"; break;

            case Resources.VirtualHardDisk: resourceSubType = "Microsoft:Hyper-V:Virtual Hard Disk"; break;

            case Resources.VirtualDvdDrive: resourceSubType = "Microsoft:Hyper-V:Synthetic DVD Drive"; break;

            case Resources.VirtualDvdDisk: resourceSubType = "Microsoft:Hyper-V:Virtual CD/DVD Disk"; break;

            case Resources.NetworkAdapter: resourceSubType = "Microsoft:Hyper-V:Synthetic Ethernet Port"; break;

            case Resources.SwitchPort: resourceSubType = "Microsoft:Hyper-V:Ethernet Connection"; break;
            }

            string      defaultSettingPath = null;
            ObjectQuery query = new ObjectQuery($"SELECT * FROM {resourcePoolClass} WHERE ResourceSubType = \"{resourceSubType}\" AND Primordial = True");

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(virtualizationScope, query))
                using (ManagementObject resourcePool = searcher.Get().First())
                    using (ManagementObjectCollection capabilitiesCollection = resourcePool.GetRelated("Msvm_AllocationCapabilities", "Msvm_ElementCapabilities", null, null, null, null, false, null))
                        using (ManagementObject capabilities = capabilitiesCollection.First())
                            foreach (ManagementObject settingAssociation in capabilities.GetRelationships("Msvm_SettingsDefineCapabilities"))
                            {
                                if ((ushort)settingAssociation["ValueRole"] == 0)
                                {
                                    defaultSettingPath = (string)settingAssociation["PartComponent"];
                                    break;
                                }
                            }

            if (defaultSettingPath == null)
            {
                throw new ManagementException("Unable to find the Default Resource Settings.");
            }

            using (ManagementObject defaultSetting = new ManagementObject(defaultSettingPath))
            {
                defaultSetting.Scope = virtualizationScope;
                defaultSetting.Get();
                return(defaultSetting);
            }
        }
        ModifyClusterMonitored(
            string virtualMachineName,
            bool onOff)
        {
            // Get management scope
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");
            int             syntheticPortCount = 0;

            // Get virtual system management service
            using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))

                // Find the virtual machine we want to modify the synthetic ethernet ports of.
                using (ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(virtualMachineName, scope))

                    // Find the virtual system setting data
                    using (ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine))

                        // Find all synthetic ethernet ports for the given virtual machine.
                        using (ManagementObjectCollection syntheticPortSettings = virtualMachineSettings.GetRelated(
                                   "Msvm_SyntheticEthernetPortSettingData",
                                   "Msvm_VirtualSystemSettingDataComponent",
                                   null, null, null, null, false, null))
                        {
                            syntheticPortCount = syntheticPortSettings.Count;

                            try
                            {
                                // Modify each port setting to update the property.
                                foreach (ManagementObject syntheticEthernetPortSetting in syntheticPortSettings)
                                {
                                    syntheticEthernetPortSetting[PropertyNames.ClusterMonitored] = onOff;

                                    // Now apply the changes to the Hyper-V server.
                                    using (ManagementBaseObject inParams = managementService.GetMethodParameters("ModifyResourceSettings"))
                                    {
                                        inParams["ResourceSettings"] = new string[] { syntheticEthernetPortSetting.GetText(TextFormat.CimDtd20) };

                                        using (ManagementBaseObject outParams =
                                                   managementService.InvokeMethod("ModifyResourceSettings", inParams, null))
                                        {
                                            WmiUtilities.ValidateOutput(outParams, scope);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Dispose of the synthetic ethernet port settings.
                                foreach (ManagementObject syntheticEthernetPortSetting in syntheticPortSettings)
                                {
                                    syntheticEthernetPortSetting.Dispose();
                                }
                            }
                        }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully modified virtual machine '{0}' so that each of its {1} synthetic ethernet port(s) " +
                                            "has {2} property modified to {3}.",
                                            virtualMachineName, syntheticPortCount, PropertyNames.ClusterMonitored, onOff));
        }
Esempio n. 29
0
        internal ManagementObject GetRelatedWmiObject(ManagementObject obj, string className)
        {
            ManagementObjectCollection col = obj.GetRelated(className);

            ManagementObjectCollection.ManagementObjectEnumerator enumerator = col.GetEnumerator();
            enumerator.MoveNext();
            return((ManagementObject)enumerator.Current);
        }
Esempio n. 30
0
 internal static ManagementObject GetMemorySettingData(this ManagementObject virtualSystemSettingData)
 {
     return
         (virtualSystemSettingData
          .GetRelated("Msvm_MemorySettingData")
          .OfType <ManagementObject>()
          .FirstOrDefault());
 }