Showing posts with label WMI. Show all posts
Showing posts with label WMI. Show all posts

Wednesday, October 31, 2007

WMI Queries on Remote Machines

Windows management instrumentation (WMI) can be used to access system management data across remote machines. You can use this to get status and configuration information on windows machines listening on the network. The classes found in the System.Management namespace helps developers to write code to access these information quickly.

The following example shows how to access LogicalMemoryConfiguration data on a remote machine.

using System;
using System.Net;
using System.Management;

namespace WMIonRemoteMachine
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the Adminstrator's Username and Password
            ConnectionOptions co = new ConnectionOptions();
            co.Username = "Administrator";
            co.Password = "password#xyz";

            //Connect to the default namespace on Remote Machine
            ManagementScope scope = new ManagementScope(@"\\[REMOTE MACHINE]\root\cimv2", co);   
       
            SelectQuery query = new SelectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

            foreach (ManagementObject mObj in searcher.Get())
            {
                foreach (System.Management.PropertyData property in mObj.Properties)
                    System.Console.WriteLine(property.Name.PadLeft(25,' ') + ": " + property.Value);
            }            
            Console.ReadLine();
        }
    }
}

OUTPUT 

  AvailableVirtualMemory: 1405028
                          Caption: Logical Memory Configuration
                     Description: Logical Memory Configuration
                             Name: LogicalMemoryConfiguration
                       SettingID: LogicalMemoryConfiguration
       TotalPageFileSpace: 2523064
     TotalPhysicalMemory: 1046512
        TotalVirtualMemory: 3569576

 

The username and password supplied in the above code should belong to an account that is a member of Administrator Group on the remote machine. If the ConnectionOptions is not set then the namespace residing on the Local System is accessed.

The default WMI namespace or schema "\root\cimv2" is queried to retrieve common system management information. WMI implements the Common Information Model (CIV) schema proposed by Distributed Management Task Force (DMTF).

Remote connections in WMI are affected by Firewall. It blocks all data requests from remote machines. If a connection fails, an exception of type System.Runtime.InteropServices.COMException is thrown in System.Management with an error message "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)". So make sure that the firewall settings are configured to allow these connections.

Friday, February 23, 2007

[How to] retrieve System Management information with WMI Queries

Windows Management Instrumentation (WMI) is the base for management data and operations on Windows Operating system. And System.Management namespace is the WMI namespace in .NET framework. The ManagementObjectSearcher class is one of the first level class objects contained within this namespace. This class can be used to retrieve a collection of ManagementObject based on a specified Win32 query. For example, it can be used to enumerate all Disk Drives, Disk Partitions, Network Adapters, Network Connections, Processes etc.

To enumerate all the disk drives and their associated properties we first instantiate a new ManagementObjectSearcher object which takes as input a WMI query. The Get() method on this object returns a collection of management objects that match this query.  

string mosQuery = "SELECT * FROM Win32_DiskDrive";

System.Management.ManagementObjectSearcher query = new System.Management.ManagementObjectSearcher(mosQuery);
foreach (System.Management.ManagementObject mObj in query.Get())
{
    foreach (System.Management.PropertyData property in mObj.Properties)
    {
        System.Console.WriteLine(property.Name + "__::" + property.Value);        
    }
}   

Sample Output (Just one object in the Collection)

Availability__::
BytesPerSector__::512
Capabilities__::System.UInt16[]
CapabilityDescriptions__::
Caption__::FUJITSU MHV2060BH
CompressionMethod__::
ConfigManagerErrorCode__::0
ConfigManagerUserConfig__::False
CreationClassName__::Win32_DiskDrive
DefaultBlockSize__::
Description__::Disk drive
DeviceID__::\\.\PHYSICALDRIVE0
ErrorCleared__::
ErrorDescription__::
ErrorMethodology__::
Index__::0
InstallDate__::
InterfaceType__::IDE
LastErrorCode__::
Manufacturer__::(Standard disk drives)
MaxBlockSize__::
MaxMediaSize__::
MediaLoaded__::True
MediaType__::Fixed hard disk media
MinBlockSize__::
Model__::FUJITSU MHV2060BH
Name__::\\.\PHYSICALDRIVE0
NeedsCleaning__::
NumberOfMediaSupported__::
Partitions__::1
PNPDeviceID__::IDE\DISKFUJITSU_MHV2060BH_______________________0085002A\5&1F698B3F&0&0.0.0
PowerManagementCapabilities__::
PowerManagementSupported__::
SCSIBus__::0
SCSILogicalUnit__::0
SCSIPort__::0
SCSITargetId__::0
SectorsPerTrack__::63
Signature__::4026531840
Size__::60011642880
Status__::OK
StatusInfo__::
SystemCreationClassName__::Win32_ComputerSystem
SystemName__::UOPONLG8BFLB1
TotalCylinders__::7296
TotalHeads__::255
TotalSectors__::117210240
TotalTracks__::1860480
TracksPerCylinder__::255

 

Or, you can also use this query,"SELECT * FROM Win32_Service WHERE Started = False", to enumerate a list of services which are not started.

The Win32_DiskDrive/Win32_Service is a WMI object that is being queried here. You can replace the above query with one of those that are listed below. I've compiled a list of management queries by inspecting the objects using WMI object browser. You can play with them or implement the same in your applications as per your requirements...

//mosQuery = "SELECT * FROM Win32_Account";
//mosQuery = "SELECT * FROM Win32_BIOS";
//mosQuery = "SELECT * FROM Win32_BootConfiguration";
//mosQuery = "SELECT * FROM Win32_Bus";
//mosQuery = "SELECT * FROM Win32_CacheMemory";
//mosQuery = "SELECT * FROM Win32_CDROMDrive";
//mosQuery = "SELECT * FROM Win32_ComputerSystem";
//mosQuery = "SELECT * FROM Win32_DesktopMonitor";
//mosQuery = "SELECT * FROM Win32_DeviceMemoryAddress";
//mosQuery = "SELECT * FROM Win32_DiskDrive";
//mosQuery = "SELECT * FROM Win32_DiskPartition";
//mosQuery = "SELECT * FROM Win32_DMAChannel";
//mosQuery = "SELECT * FROM Win32_Environment";
//mosQuery = "SELECT * FROM Win32_Fan";
//mosQuery = "SELECT * FROM Win32_IDEController";
//mosQuery = "SELECT * FROM Win32_IRQResource";
//mosQuery = "SELECT * FROM Win32_Keyboard";
//mosQuery = "SELECT * FROM Win32_LoadOrderGroup";
//mosQuery = "SELECT * FROM Win32_LogicalDisk";
//mosQuery = "SELECT * FROM Win32_LogicalMemoryConfiguration";
//mosQuery = "SELECT * FROM Win32_LogicalProgramGroup";
//mosQuery = "SELECT * FROM Win32_MemoryArray";
//mosQuery = "SELECT * FROM Win32_MemoryDevice";
//mosQuery = "SELECT * FROM Win32_MotherBoardDevice";
//mosQuery = "SELECT * FROM Win32_NetworkAdapter";
//mosQuery = "SELECT * FROM Win32_NetworkConnections";
//mosQuery = "SELECT * FROM Win32_NTEventLogFile";
//mosQuery = "SELECT * FROM Win32_NTLogEvent";
//mosQuery = "SELECT * FROM Win32_OperatingSystem";
//mosQuery = "SELECT * FROM Win32_PCMCIAController";
//mosQuery = "SELECT * FROM Win32_PnPEntity";
//mosQuery = "SELECT * FROM Win32_PointingDevice";
//mosQuery = "SELECT * FROM Win32_PortableBattery";
//mosQuery = "SELECT * FROM Win32_PortResource";
//mosQuery = "SELECT * FROM Win32_POTSModem";
//mosQuery = "SELECT * FROM Win32_Printer";
//mosQuery = "SELECT * FROM Win32_Process";
//mosQuery = "SELECT * FROM Win32_Processor";
//mosQuery = "SELECT * FROM Win32_SCSIController";
//mosQuery = "SELECT * FROM Win32_SerialPort";
//mosQuery = "SELECT * FROM Win32_Service";
//mosQuery = "SELECT * FROM Win32_share";
//mosQuery = "SELECT * FROM Win32_SoundDevice";
//mosQuery = "SELECT * FROM Win32_SystemDriver";
//mosQuery = "SELECT * FROM Win32_SystemUsers";
//mosQuery = "SELECT * FROM Win32_TemperatureProbe";
//mosQuery = "SELECT * FROM Win32_TimeZone";
//mosQuery = "SELECT * FROM Win32_USBController";
//mosQuery = "SELECT * FROM Win32_USBHub";
//mosQuery = "SELECT * FROM Win32_UserAccount";
//mosQuery = "SELECT * FROM Win32_VideoController";        

Happy Coding !!!