Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SWbemObject.GetObjectText_ C# Equivilent?

Posted on 2011-03-17
2
Medium Priority
?
629 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

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

604 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