Solved

SWbemObject.GetObjectText_ C# Equivilent?

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

929 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

8 Experts available now in Live!

Get 1:1 Help Now