Solved

SWbemObject.GetObjectText_ C# Equivilent?

Posted on 2011-03-17
2
603 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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now