views:

77

answers:

1

Hi,

I need to determine the sql server instances (local) as part on an installer.

Does anyone have any code how I can do this with WMI and Delphi?

JD.

A: 

@JD, to get the Sql Server instances using the WMi you must use the WMI Provider for Configuration Management Classes, see the ServerSettings class.

Check this sample code, with 2 different methods to accomplish the same task.

program GetWMI_SqlInstancesInfo;

{$APPTYPE CONSOLE}

uses
  Windows,
  Classes,
  ActiveX,
  Variants,
  SysUtils,
  WbemScripting_TLB in '..\..\Documents\RAD Studio\5.0\Imports\WbemScripting_TLB.pas';

procedure  WmiHelper(RootStr,WmiQuery:String);
var
  WMIServices  : ISWbemServices;
  WMILocator   : ISWbemLocator;
  Root         : ISWbemObjectSet;
  SWbemObject  : ISWbemObject;
  Item         : IEnumVariant;
  rgVar        : OleVariant;
  pCelFetched  : Cardinal;
begin
  WMILocator := CoSWbemLocator.Create();
  WMIServices := WMILocator.ConnectServer('.', RootStr,'', '', '', '', 0, nil);    //
  Root := WMIServices.ExecQuery(WmiQuery,'WQL', 0, nil);
  Item :=  (Root._NewEnum) as IEnumVariant;
    while  (Item.Next(1, rgVar, pCelFetched) = S_OK) do
    begin
      SWbemObject := IUnknown(rgVar) as ISWBemObject;
      if (SWbemObject <> nil) then
      begin
        SWbemObject.Properties_;
        Writeln(SWbemObject.GetObjectText_(0));
      end;
    end;
end;

//option 1 , shows all properties of the class just by running the query

procedure  GetWMISQLInstancesInfo;
begin
  WmiHelper('root\Microsoft\SqlServer\ComputerManagement','SELECT * FROM ServerSettings');
  //WmiHelper('root\Microsoft\SqlServer\ComputerManagement','SELECT * FROM SqlServiceAdvancedProperty where SQLServiceType = 1');
end;


//option 2 , in this case you must know the properties names to get the info
    procedure  GetWMISQLInstancesInfo2;
    var
      WMIServices: ISWbemServices;
      Root       : ISWbemObjectSet;
      Item       : Variant;
      I          : Integer;
    begin
      WMIServices := CoSWbemLocator.Create.ConnectServer('.', 'root\Microsoft\SqlServer\ComputerManagement','', '', '', '', 0, nil);
      Root  := WMIServices.ExecQuery('SELECT * FROM ServerSettings','WQL', 0, nil);
      for I := 0 to Root.Count - 1 do
      begin
        Item := Root.ItemIndex(I);
        Writeln('Instance Name '+VarToStr(Item.InstanceName));
      end;
    End;

    begin
     try
        CoInitialize(nil);
        try
          GetWMISQLInstancesInfo;
          GetWMISQLInstancesInfo2;
          Readln;
        finally
          CoUninitialize;
        end;
     except
        on E:Exception do
        Begin
            Writeln(E.Classname, ': ', E.Message);
            Readln;
        End;
      end;
    end.
RRUZ