?
Solved

SWbemObject.GetObjectText_ C# Equivilent?

Posted on 2011-03-17
2
Medium Priority
?
626 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 2000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

801 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