예제 #1
1
        public static ManagementObject GetResourceAllocationsettingData(
            ManagementObject vm,
            ushort resourceType,
            string resourceSubType,
            string otherResourceType)
        {
            // vm->vmsettings->RASD for IDE controller
            ManagementObject managementObjectRASD = null;
            ManagementObjectCollection settingDatas = vm.GetRelated("Msvm_VirtualSystemsettingData");
            foreach (ManagementObject settingData in settingDatas)
            {
                // retrieve the rasd
                ManagementObjectCollection collectionOfRASDs = settingData.GetRelated("Msvm_ResourceAllocationsettingData");
                foreach (ManagementObject rasdInstance in collectionOfRASDs)
                {
                    if (Convert.ToInt16(rasdInstance["ResourceType"], CultureInfo.InvariantCulture) == resourceType)
                    {
                        // found the matching type
                        if (resourceType == ResourceType.Other)
                        {
                            if (rasdInstance["OtherResourceType"].ToString() == otherResourceType)
                            {
                                managementObjectRASD = rasdInstance;
                                break;
                            }
                        }
                        else
                        {
                            if (rasdInstance["ResourceSubType"].ToString() == resourceSubType)
                            {
                                managementObjectRASD = rasdInstance;
                                break;
                            }
                        }
                    }
                }
            }

            return managementObjectRASD;
        }
예제 #2
0
        /// <summary>
        /// Gets the data for a given snapshot that belongs to the given virtual machine..
        /// </summary>
        /// <param name="virtualMachine">The virtual machine object.</param>
        /// <param name="snapshotName">The name of the snapshot that should be obtained.</param>
        /// <returns>The snapshot data object or <see langword="null" /> if no snapshot could be found.</returns>
        public static ManagementObject GetSnapshotData(ManagementObject virtualMachine, string snapshotName)
        {
            ManagementObjectCollection vmSettings = virtualMachine.GetRelated(
                "Msvm_VirtualSystemsettingData",
                "Msvm_PreviousSettingData",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null);

            ManagementObject vmSetting = null;
            foreach (ManagementObject instance in vmSettings)
            {
                var name = (string)instance["ElementName"];
                if (string.Equals(snapshotName, name, StringComparison.Ordinal))
                {
                    vmSetting = instance;
                    break;
                }
            }

            return vmSetting;
        }
예제 #3
0
        // Expects a Win32_DiskDrive object
        // http://msdn.microsoft.com/en-us/library/aa394132%28v=VS.85%29.aspx
        internal Volume(ManagementObject o)
        {
            if (o.ClassPath.ClassName != "Win32_DiskDrive")
                throw new ArgumentException (o.ClassPath.ClassName, "o");

            Uuid = o.Str ("PNPDeviceID");
            Name = o.Str ("Caption");

            // Get USB vendor/product ids from the associated CIM_USBDevice
            // This way of associating them (via a substring of the PNPDeviceID) is quite a hack; patches welcome
            var match = regex.Match (Uuid);
            if (match.Success) {
                string query = String.Format ("SELECT * FROM CIM_USBDevice WHERE DeviceID LIKE '%{0}'", match.Groups[1].Captures[0].Value);
                UsbDevice = HardwareManager.Query (query).Select (u => new UsbDevice (u)).FirstOrDefault ();
            }

            // Get MountPoint and more from the associated LogicalDisk
            // FIXME this assumes one partition for the device
            foreach (ManagementObject partition in o.GetRelated ("Win32_DiskPartition")) {
                foreach (ManagementObject disk in partition.GetRelated ("Win32_LogicalDisk")) {
                    //IsMounted = (bool)ld.GetPropertyValue ("Automount") == true;
                    //IsReadOnly = (ushort) ld.GetPropertyValue ("Access") == 1;
                    MountPoint = disk.Str ("Name") + "/";
                    FileSystem = disk.Str ("FileSystem");
                    Capacity = (ulong) disk.GetPropertyValue ("Size");
                    Available = (long)(ulong)disk.GetPropertyValue ("FreeSpace");
                    return;
                }
            }
        }
        GetReplicationServiceSettings(
            ManagementObject replicationService)
        {
            using (ManagementObjectCollection settingsCollection =
                    replicationService.GetRelated("Msvm_ReplicationServiceSettingData"))
            {
                ManagementObject replicationServiceSettings = 
                    WmiUtilities.GetFirstObjectFromCollection(settingsCollection);

                return replicationServiceSettings;
            }
        }
예제 #5
0
 public static Disk getDisk(string driveLetter)
 {
     var disks = new ManagementObject("Win32_LogicalDisk.DeviceID='" + driveLetter + ":'");
     foreach (ManagementObject diskPart in disks.GetRelated("Win32_DiskPartition"))
     {
         foreach (ManagementObject diskDrive in diskPart.GetRelated("Win32_DiskDrive"))
         {
             Disk disk = new Disk();
             disk.driveLetter = driveLetter;
             disk.productName = diskDrive["Caption"].ToString().Replace(" ATA Device", "");
             disk.pnpId = diskDrive["PnPDeviceID"].ToString();
             return disk;
         }
     }
     return null;
 }
        public static string GetSerialNumber(string DriveLetter)
        {
            DriveLetter = DriveLetter.ToUpper();
            string  temp = string.Empty;
            string ans = string.Empty;
            string[] parts;
            //get the Logical Disk for that drive letter
            ManagementObject wmi_ld = new ManagementObject("win32_logicaldisk.deviceid=\"" + DriveLetter + "\"");
            //get the associated DiskPartition
            foreach (ManagementObject DiskPartition in wmi_ld.GetRelated("Win32_DiskPartition"))
            {
                //get the associated DiskDrive
                foreach (ManagementObject DiskDrive in DiskPartition.GetRelated("Win32_DiskDrive"))
                {
                    /*There is a bug in WinVista that corrupts some of the fields
                    of the Win32_DiskDrive class if you instantiate the class via
                    its primary key (as in the example above) and the device is
                    a USB disk. Oh well... so we have go thru this extra step*/
                    ManagementClass wmi = new ManagementClass("Win32_DiskDrive");
                    /*loop thru all of the instances. This is silly, we shouldn't
                     *have to loop thru them all, when we know which one we want.*/
                    foreach (ManagementObject obj in wmi.GetInstances())
                    {
                        // do the DeviceID fields match?
                        if (obj["DeviceID"].ToString() == DiskDrive["DeviceID"].ToString())
                        {
                            //the serial number is embedded in the PnPDeviceID
                            temp = obj["PnPDeviceID"].ToString();
                            if (!temp.StartsWith("USBSTOR"))
                            {
                                System.Windows.Forms.MessageBox.Show(DriveLetter + " doesn't appear to be USB Device");
                                return string.Empty;
                            }
                            parts = temp.Split("\\&".ToCharArray());
                            //The serial number should be the next to the last element
                            ans = parts[parts.Length - 2];
                        }

                    }
                }
            }
            return ans;
        }
        GetDefaultObjectFromResourcePool(
            ManagementObject resourcePool,
            ManagementScope scope)
        {
            //
            // The default object is associated with the Msvm_AllocationCapabilities object that 
            // is associated to the resource pool.
            //
            string defaultSettingPath = null;

            using (ManagementObjectCollection capabilitiesCollection = 
                   resourcePool.GetRelated("Msvm_AllocationCapabilities",
                                           "Msvm_ElementCapabilities",
                                           null, null, null, null, false, null))
            using (ManagementObject capabilities =
                   WmiUtilities.GetFirstObjectFromCollection(capabilitiesCollection))
            {
                foreach (ManagementObject settingAssociation in 
                         capabilities.GetRelationships("Msvm_SettingsDefineCapabilities"))
                {
                    using (settingAssociation)
                    {
                        if ((ushort)settingAssociation["ValueRole"] == 0)
                        {
                            defaultSettingPath = (string)settingAssociation["PartComponent"];
                            break;
                        }
                    }
                }
            }

            if (defaultSettingPath == null)
            {
                throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                            "Unable to find the default settings!"));
            }

            ManagementObject defaultSetting = new ManagementObject(defaultSettingPath);
            defaultSetting.Scope = scope;
            defaultSetting.Get();

            return defaultSetting;
        }
        GetGuestFileService(
            ManagementObject guestServiceInterfaceComponent)
        {
            ManagementObject guestFileService;

            using (ManagementObjectCollection guestFileServices =
                guestServiceInterfaceComponent.GetRelated(
                    "Msvm_GuestFileService",
                    "Msvm_RegisteredGuestService",
                    null,
                    null,
                    null,
                    null,
                    false,
                    null))
            {
                guestFileService = WmiUtilities.GetFirstObjectFromCollection(
                    guestFileServices);
            }

            return guestFileService;
        }
        GetMigrationServiceSettings(
            ManagementObject service
            )
        {
            ManagementObject serviceSetting = null;
            using (ManagementObjectCollection settingCollection =
                service.GetRelated("Msvm_VirtualSystemMigrationServiceSettingData"))
            {
                foreach (ManagementObject mgmtObj in settingCollection)
                {
                    serviceSetting = mgmtObj;
                    break;
                }
            }

            return serviceSetting;
        }
        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;
        }
        /// <summary>
        /// The get computer keyboard.
        /// </summary>
        /// <param name="vm">
        /// The vm.
        /// </param>
        /// <returns>
        /// The <see cref="ManagementObject"/>.
        /// </returns>
        private static ManagementObject GetComputerKeyboard(ManagementObject vm)
        {
            ManagementObjectCollection keyboardCollection = vm.GetRelated(
                "Msvm_Keyboard", "Msvm_SystemDevice", null, null, "PartComponent", "GroupComponent", false, null);

            ManagementObject keyboard = null;

            foreach (ManagementObject instance in keyboardCollection)
            {
                keyboard = instance;
                break;
            }

            return keyboard;
        }
예제 #12
0
 internal ManagementObject GetRelatedWmiObject(ManagementObject obj, string className)
 {
     ManagementObjectCollection col = obj.GetRelated(className);
     ManagementObjectCollection.ManagementObjectEnumerator enumerator = col.GetEnumerator();
     enumerator.MoveNext();
     return (ManagementObject)enumerator.Current;
 }
        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;
        }
예제 #14
0
        public static ManagementObject GetVirtualSystemSettingData(ManagementObject vm)
        {
            ManagementObject virtualMachineSetting = null;
            ManagementObjectCollection virtualMachineSettings = vm.GetRelated(
                "Msvm_VirtualSystemSettingData",
                "Msvm_SettingsDefineState",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null);

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

            foreach (ManagementObject instance in virtualMachineSettings)
            {
                virtualMachineSetting = instance;
                break;
            }

            return virtualMachineSetting;
        }
        PrintOutOfPolicyVHDsInPool(
            ManagementObject resourcePool)
        {
            //Get Logical disks in the pool
            ManagementObjectCollection logicalDisks = resourcePool.GetRelated(
                "Msvm_LogicalDisk",
                "Msvm_ElementAllocatedFromPool",
                null, null, null, null, false, null);

            foreach (ManagementObject logicalDisk in logicalDisks)
            using (logicalDisk)
            {
                //Check the operational status on the logical disk
                UInt16[] opStatus = (UInt16[])logicalDisk["OperationalStatus"];
                if (opStatus[0] != OperationalStatusOK)
                {                            
                    foreach (UInt16 opState in opStatus)
                    {
                        //Check for the specific QOS related opcode
                        if (opState == OperationalStatusInsufficientThroughput)
                        {
                            // Get the SASD associated with the logical disk to get the vhd name.
                            using (ManagementObjectCollection sasds = logicalDisk.GetRelated(
                                "Msvm_StorageAllocationSettingData",
                                "Msvm_SettingsDefineState",
                                null, null, null, null, false, null))
                            // There is only one sasd associated with a logical disk.
                            foreach (ManagementObject sasd in sasds)
                            using (sasd)
                            {
                                string vhdPath = ((string[])sasd["HostResource"])[0];
                                string vhdName = Path.GetFileName(vhdPath);
                                Console.WriteLine("    VHD Not in Policy: {0}", vhdName);
                            }
                        }
                    }
                }
            }
        }
        AddSyntheticAdapter(
            ManagementObject virtualMachine,
            ManagementScope scope)
        {
            using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))
            using (ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine))
            //
            // Get the default Synthetic Adapter object, then modify its properties.
            //
            using (ManagementObject adapterToAdd = GetDefaultSyntheticAdapter(scope))
            {
                adapterToAdd["VirtualSystemIdentifiers"] = new string[] { Guid.NewGuid().ToString("B") };
                adapterToAdd["ElementName"] = "Network Adapter";
                adapterToAdd["StaticMacAddress"] = false;

                //
                // Now add it to the virtual machine.
                //
                using (ManagementBaseObject addAdapterInParams = managementService.GetMethodParameters("AddResourceSettings"))
                {
                    addAdapterInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
                    addAdapterInParams["ResourceSettings"] = new string[] { adapterToAdd.GetText(TextFormat.WmiDtd20) };

                    using (ManagementBaseObject addAdapterOutParams =
                           managementService.InvokeMethod("AddResourceSettings", addAdapterInParams, null))
                    {
                        WmiUtilities.ValidateOutput(addAdapterOutParams, scope);

                        //
                        // Get the created network adapter from the output parameters.
                        //
                        ManagementObject addedAdapter;
                        if (addAdapterOutParams["ResultingResourceSettings"] != null)
                        {
                            addedAdapter = new ManagementObject(
                                ((string[])addAdapterOutParams["ResultingResourceSettings"])[0]);
                            addedAdapter.Get();
                        }
                        else
                        {
                            using (ManagementObject job = new ManagementObject((string)addAdapterOutParams["Job"]))
                            {
                                addedAdapter = WmiUtilities.GetFirstObjectFromCollection(job.GetRelated(null,
                                    "Msvm_AffectedJobElement", null, null, null, null, false, null));
                            }
                        }

                        return addedAdapter;
                    }
                }
            }
        }
        /// <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;
        }
예제 #18
0
        /// <summary>
        /// Gets the last snapshot of the named VM snapshot tree
        /// </summary>
        /// <param name="vm">The current management object for the VM</param>
        /// <returns>The object containing the details of the snapshot</returns>
        private ManagementObject GetLastVirtualSystemSnapshot(ManagementObject vm)
        {
            ManagementObjectCollection settings = vm.GetRelated(
                "Msvm_VirtualSystemsettingData",
                "Msvm_PreviousSettingData",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null);

            ManagementObject virtualSystemsetting = null;
            foreach (ManagementObject setting in settings)
            {
                this.LogBuildMessage(string.Format(CultureInfo.InvariantCulture, "Getting last snapshot from server {0} of name [{1}]", setting.Path.Path, setting["ElementName"]));
                virtualSystemsetting = setting;
            }

            return virtualSystemsetting;
        }
예제 #19
0
 private static ManagementObject getSettingData(string relatedClass, string relationshipClass, ManagementObject mObject, ManagementScope mScope)
 {
     using (ManagementObjectCollection mCollection = mObject.GetRelated(relatedClass, relationshipClass, null, null, null, null, false, null))
     {
         foreach (ManagementObject mReturn in mCollection)
         {
             return mReturn;
         }
     }
     return null;
 }
예제 #20
0
        /// <summary>
        /// Gets the virtual machine's configuration settings object.
        /// </summary>
        /// <param name="virtualMachine">The virtual machine.</param>
        /// <returns>The virtual machine's configuration object.</returns>
        public static ManagementObject GetVirtualMachineSettings(ManagementObject virtualMachine)
        {
            using (ManagementObjectCollection settingsCollection =
                    virtualMachine.GetRelated("Msvm_VirtualSystemSettingData", "Msvm_SettingsDefineState",
                    null, null, null, null, false, null))
            {
                ManagementObject virtualMachineSettings =
                    WMIUtils.GetFirstObjectFromCollection(settingsCollection);

                return virtualMachineSettings;
            }
        }
예제 #21
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();
            }
        }
        GetEthernetSwitchPortAclSettingData(
            ManagementObject ethernetConnection,
            string ipAddress,
            ManagementScope scope)
        {
            using (ManagementObjectCollection portAclCollection = 
                ethernetConnection.GetRelated("Msvm_EthernetSwitchPortAclSettingData",
                    "Msvm_EthernetPortSettingDataComponent",
                    null, null, null, null, false, null))
            {
                if (portAclCollection.Count == 0)
                {
                    throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                        "No associated Msvm_EthernetSwitchPortAclSettingData could be found"));
                }

                string address = ipAddress;
                byte addressPrefixLength = 32;
                
                //
                // If the IP address is in the form "A.B.C.D/N", extract the address and prefix 
                // length.
                //
                string[] addressParts = ipAddress.Split(new char[] {'/', '\\'});

                if (addressParts.Length == 2)
                {
                    address = addressParts[0];
                    addressPrefixLength = byte.Parse(addressParts[1], CultureInfo.InvariantCulture);
                }

                ManagementObject foundPortAcl = null;

                foreach (ManagementObject portAcl in portAclCollection)
                {
                    if ((portAcl["RemoteAddress"].ToString() == address) &&
                        ((byte)portAcl["RemoteAddressPrefixLength"] == addressPrefixLength))
                    {
                        foundPortAcl = portAcl;
                        break;
                    }
                }

                if (foundPortAcl == null)
                {
                    throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                        "No associated Msvm_EthernetSwitchPortAclSettingData could be found " +
                        "for IP address \"{0}\"", ipAddress));
                }
                
                return foundPortAcl;
            }
        }
예제 #23
0
        /// <summary>
        /// Gets the array of Msvm_StorageAllocationSettingData of VHDs associated with the given virtual
        /// machine settings.
        /// </summary>
        /// <param name="virtualMachineSettings">A ManagementObject representing the settings of a virtual
        /// machine or snapshot.</param>
        /// <returns>Array of Msvm_StorageAllocationSettingData of VHDs associated with the given settings.</returns>
        public static ManagementObject[] GetVhdSettingsFromVirtualMachineSettings(
            ManagementObject virtualMachineSettings)
        {
            const UInt16 SASDResourceTypeLogicalDisk = 31;

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

            //
            // Get all the SASDs (Msvm_StorageAllocationSettingData)
            // and look for VHDs.
            //
            using (ManagementObjectCollection sasdCollection =
                virtualMachineSettings.GetRelated("Msvm_StorageAllocationSettingData",
                    "Msvm_VirtualSystemSettingDataComponent",
                    null, null, null, null, false, null))
            {
                foreach (ManagementObject sasd in sasdCollection)
                {
                    if ((UInt16)sasd["ResourceType"] == SASDResourceTypeLogicalDisk)
                    {
                        sasdList.Add(sasd);
                    }
                    else
                    {
                        sasd.Dispose();
                    }
                }
            }

            if (sasdList.Count == 0)
            {
                return null;
            }
            else
            {
                return sasdList.ToArray();
            }
        }
예제 #24
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;
        }
예제 #25
0
        private void PrintSite(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);
            }

            Console.WriteLine("scriptmap:");
            foreach (var scriptMap in (ManagementBaseObject[]) site["ScriptMaps"]) {
                Console.WriteLine("  props:");
                foreach (var prop in scriptMap.Properties) {
                    Console.WriteLine("    {0}: {1}", prop.Name, prop.Value);
                }
                Console.WriteLine("  system props:");
                foreach (var prop in scriptMap.SystemProperties) {
                    Console.WriteLine("    {0}: {1}", prop.Name, prop.Value);
                }
            }
        }
        AddSyntheticFcAdapter(
            ManagementObject virtualMachine,
            ManagementScope scope,
            WorldWideName wwnA,
            WorldWideName wwnB)
        {
            using (ManagementObject managementService =
                   WmiUtilities.GetVirtualMachineManagementService(scope))
            using (ManagementObject virtualMachineSettings =
                   WmiUtilities.GetVirtualMachineSettings(virtualMachine))
            //
            // Get the default Synthetic Adapter object, then modify its properties.
            //
            using (ManagementObject adapterToAdd = GetDefaultSyntheticFcAdapter(scope))
            {
                adapterToAdd["ElementName"] = FibreChannelUtilities.FcDeviceName;
                adapterToAdd["VirtualPortWWPN"] = wwnA.PortName;
                adapterToAdd["VirtualPortWWNN"] = wwnA.NodeName;
                adapterToAdd["SecondaryWWPN"] = wwnB.PortName;
                adapterToAdd["SecondaryWWNN"] = wwnB.NodeName;

                //
                // Now add it to the virtual machine.
                //
                using (ManagementBaseObject addAdapterInParams =
                       managementService.GetMethodParameters("AddResourceSettings"))
                {
                    addAdapterInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
                    addAdapterInParams["ResourceSettings"] = new string[] { adapterToAdd.GetText(
                                                                            TextFormat.WmiDtd20) };

                    using (ManagementBaseObject addAdapterOutParams =
                           managementService.InvokeMethod("AddResourceSettings",
                                                          addAdapterInParams,
                                                          null))
                    {
                        WmiUtilities.ValidateOutput(addAdapterOutParams, scope);

                        //
                        // Get the created FC adapter from the output parameters.
                        //
                        ManagementObject addedAdapter;
                        if (addAdapterOutParams["ResultingResourceSettings"] != null)
                        {
                            addedAdapter = new ManagementObject(
                                ((string[])addAdapterOutParams["ResultingResourceSettings"])[0]);

                            addedAdapter.Get();
                        }
                        else
                        {
                            using (ManagementObject job =
                                   new ManagementObject((string)addAdapterOutParams["Job"]))
                            {
                                addedAdapter =
                                    WmiUtilities.GetFirstObjectFromCollection(job.GetRelated(null,
                                        "Msvm_AffectedJobElement", null, null, null, null, false, null));
                            }
                        }

                        return addedAdapter;
                    }
                }
            }
        }
        RealizePvm(
            string pvmName
            )
        {
            ManagementObject vm = null;
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject pvm = WmiUtilities.GetPlannedVirtualMachine(pvmName, scope))
            using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))
            using (ManagementBaseObject inParams =
                managementService.GetMethodParameters("RealizePlannedSystem"))
            {
                inParams["PlannedSystem"] = pvm.Path;

                Console.WriteLine("Realizing Planned Virtual Machine \"{0}\" ({1})...",
                        pvm["ElementName"], pvm["Name"]);

                using (ManagementBaseObject outParams =
                    managementService.InvokeMethod("RealizePlannedSystem", inParams, null))
                {
                    if (WmiUtilities.ValidateOutput(outParams, scope, true, true))
                    {
                        using (ManagementObject job =
                            new ManagementObject((string)outParams["Job"]))
                        using (ManagementObjectCollection pvmCollection =
                            job.GetRelated("Msvm_ComputerSystem",
                                "Msvm_AffectedJobElement", null, null, null, null, false, null))
                        {
                            vm = WmiUtilities.GetFirstObjectFromCollection(pvmCollection);
                        }
                    }
                }
            }

            return vm;
        }
 GetSnapshotSettings(
     ManagementObject virtualMachine)
 {
     return virtualMachine.GetRelated("Msvm_VirtualSystemSettingData",
         "Msvm_ElementSettingData", null, null, null, null, false, null);
 }