How do I use WMI with Delphi without drastically increasing the application's file size?

Posted by Mick on Stack Overflow See other posts from Stack Overflow or by Mick
Published on 2010-05-03T21:24:14Z Indexed on 2010/05/03 21:28 UTC
Read the original article Hit count: 601

Filed under:
|

I am using Delphi 2010, and when I created a console application that prints "Hello World", it takes 111 kb. If I want to query WMI with Delphi, I add WBEMScripting_TLB, ActiveX, and Variants units to my project. If I perform a simple WMI query, my executable size jumps to 810 kb. I

Is there anyway to query WMI without such a large addition to the size of the file? Forgive my ignorance, but why do I not have this issue with C++?

Here is my code:

program WMITest;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  WBEMScripting_TLB,
  ActiveX,
  Variants;

function GetWMIstring(wmiHost, root, wmiClass, wmiProperty: string): string;
var
  Services: ISWbemServices;
  SObject: ISWbemObject;
  ObjSet: ISWbemObjectSet;
  SProp: ISWbemProperty;
  Enum: IEnumVariant;
  Value: Cardinal;
  TempObj: OLEVariant;
  loc: TSWbemLocator;
  SN: string;
  i: integer;
begin
  Result := '';
  i := 0;
  try
    loc := TSWbemLocator.Create(nil);
    Services := Loc.ConnectServer(wmiHost, root {'root\cimv2'}, '', '', '', '',
      0, nil);
    ObjSet := Services.ExecQuery('SELECT * FROM ' + wmiClass, 'WQL',
      wbemFlagReturnImmediately and wbemFlagForwardOnly, nil);
    Enum := (ObjSet._NewEnum) as IEnumVariant;
    if not VarIsNull(Enum) then
      try
        while Enum.Next(1, TempObj, Value) = S_OK do
        begin
          try
            SObject := IUnknown(TempObj) as ISWBemObject;
          except SObject := nil;
          end;
          TempObj := Unassigned;
          if SObject <> nil then
          begin
            SProp := SObject.Properties_.Item(wmiProperty, 0);
            SN := SProp.Get_Value;
            if not VarIsNull(SN) then
            begin
              if varisarray(SN) then
              begin
                for i := vararraylowbound(SN, 1) to vararrayhighbound(SN, 1) do
                  result := vartostr(SN[i]);
              end
              else
                Result := SN;
              Break;
            end;
          end;
        end;
        SProp := nil;
      except
        Result := '';
      end
    else
      Result := '';
    Enum := nil;
    Services := nil;
    ObjSet := nil;
  except
    on E: Exception do
      Result := e.message;
  end;
end;

begin
  try
    WriteLn('hello world');
    WriteLn(GetWMIstring('.', 'root\CIMV2', 'Win32_OperatingSystem',
      'Caption'));
    WriteLn('done');

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

© Stack Overflow or respective owner

Related posts about delphi

Related posts about wmi