Solved

SWbemObject.GetObjectText_ C# Equivilent?

Posted on 2011-03-17
2
618 Views
Last Modified: 2013-12-17
Hi,

Is there an equivilent to the following object:

http://msdn.microsoft.com/en-us/library/aa393775%28v=vs.85%29.aspx
SWbemObject.GetObjectText_ Method



So in VBScript this would output something like:

' ----- Script start ------

Option Explicit
Dim objWMIService, objItem, colItems, strComputer

On Error Resume Next
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")

For Each objItem in colItems
      WScript.Echo objItem.getObjectText_
Next

WSCript.Quit

' ----- Script end ------------



instance of Win32_LogicalDisk
{
      Access = 0;
      Caption = "C:";
      Compressed = FALSE;
      CreationClassName = "Win32_LogicalDisk";
      Description = "Local Fixed Disk";
      DeviceID = "C:";
      DriveType = 3;
      FileSystem = "NTFS";
      FreeSpace = "27016232960";
      MaximumComponentLength = 255;
      MediaType = 12;
      Name = "C:";
      QuotasDisabled = TRUE;
      QuotasIncomplete = FALSE;
      QuotasRebuilding = FALSE;
      Size = "53684989952";
      SupportsDiskQuotas = TRUE;
      SupportsFileBasedCompression = TRUE;
      SystemCreationClassName = "Win32_ComputerSystem";
      SystemName = "LEVEL3";
      VolumeDirty = FALSE;
      VolumeName = "OS";
      VolumeSerialNumber = "8CBC64AB";
};


So it would format the text like it does using WbemTest.


So I am looking for the C# equivilent of:

WScript.Echo objItem.getObjectText_


Thanks,

Ward.

0
Comment
Question by:whorsfall
2 Comments
 
LVL 19

Expert Comment

by:Shahan Ayyub
ID: 35168407
Hi!

Did you check this link: (ManagementObjectSearcher Class)
http://www.codeproject.com/KB/system/DeviceStatus.aspx
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 35175163
Here is an example that I use to show WMI query in C#:

//Add a reference to System.Management.dll to the project.

using System;
using System.Management;
using System.Collections.Generic;

namespace CSharp.CodeSnippet.WMI
{

    public class Win32_LogicalDisk : BaseWmiObject<Win32_LogicalDisk>
    {

        public enum DiskType
        {
            Unknown,
            NoRootDirectory,
            Removable,
            Local,
            Network,
            CD,
            RAM
        }

        public string Name;
        public long Freespace;
        public long Size;
        public DiskType DriveType;
        public string VolumeName;
        public string VolumeSerialNumber;

        public Win32_LogicalDisk(ManagementObject managementObject)
            : base(managementObject)
        {
        }

        public Win32_LogicalDisk()
        {
        }

        /// <summary>
        /// Get drive volumes using a WMI query.
        /// </summary>
        public List<Win32_LogicalDisk> GetList()
        {
            return base.ExecuteQuery();
        }

        /// <summary>
        /// Get drive volumes using a WMI query on a remote machine.
        /// </summary>
        public List<Win32_LogicalDisk> GetList(string machineName, string userName, string password)
        {
            return base.ExecuteQuery(machineName, userName, password);
        }

    }

}

Open in new window


Base class:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
using System.Reflection;

namespace CSharp.CodeSnippet.WMI
{

    public class BaseWmiObject<T> where T : class
    {

        public BaseWmiObject(ManagementObject managementObject)
        {
            this.ManagementObject = managementObject;
        }

        public BaseWmiObject()
        {               
        }

        internal ManagementObject ManagementObject { get; private set; }

        private void ConfigureScope(ManagementObjectSearcher searcher, string machineName, string userName, string password)
        {
            if (userName != null && password != null && userName.Trim().Length > 0 && userName.Trim().Length > 0)
            {
                ManagementPath path = new ManagementPath();

                if (machineName != ".")
                    path.Server = string.Format(@"\\{0}\root\cimv2", machineName.TrimStart('\\'));

                ConnectionOptions options = new ConnectionOptions();
                options.Username = userName;
                options.Password = password;

                ManagementScope scope = new ManagementScope(path, options);

                searcher.Scope = scope;
            }
        }


        protected List<T> ExecuteQuery()
        {
            return ExecuteQuery(null, null, null);
        }

        protected List<T> ExecuteQuery(string machineName, string userName, string password)
        {
            string query = "Select * From " + this.GetType().Name;

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            // If machine name, user name, and password are passed, configure the scope to execute the query on the remote machine.
            if (!string.IsNullOrEmpty(machineName))
            {
                this.ConfigureScope(searcher, machineName, userName, password);
            }

            List<T> list = new List<T>();

            // Execute the query to get all the WMI objects.
            ManagementObjectCollection result = searcher.Get();

            // Build a list of type-specific objects.
            foreach (ManagementObject obj in result)
            {
                T entry = (T) Activator.CreateInstance(this.GetType(), obj);

                // Get all the public fields.
                FieldInfo[] fieldList = this.GetType().GetFields();

                foreach (FieldInfo field in fieldList)
                    field.SetValue(entry, ConvertValue(obj[field.Name], field.FieldType));

                list.Add(entry);
            }
            return list;
        }

        protected object InvokeMethod(params object[] parameters)
        {
            // Reflect the method to call from the caller's name.
            StackFrame sf = new StackFrame(1);
            string method = sf.GetMethod().Name;

            return this.ManagementObject.InvokeMethod(method, parameters);
        }

        protected object ConvertValue(object value, Type type)
        {
            if (value != null)
            {
                if (type == typeof(DateTime))
                {
                    string time = value.ToString();
                    time = time.Substring(0, time.IndexOf("."));
                    return DateTime.ParseExact(time, "yyyyMMddHHmmss", null);
                }
                else if (type == typeof(long))
                    return Convert.ToInt64(value);
                else if (type == typeof(int))
                    return Convert.ToInt32(value);
                else if (type == typeof(short))
                    return Convert.ToInt16(value);
                else if (type == typeof(string))
                    return value.ToString();
                else if (type.BaseType == typeof(Enum))
                    return value;
            }
            return null;
        }

    }

}

Open in new window

0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question