Recent

Author Topic: Does FreePascal have a WMI Query library?  (Read 31503 times)

CM630

  • Hero Member
  • *****
  • Posts: 1641
  • Не съм сигурен, че те разбирам.
    • http://sourceforge.net/u/cm630/profile/
Re: Does FreePascal have a WMI Query library?
« Reply #30 on: February 05, 2026, 01:02:14 pm »
I added Attempts and RetryInterval parameters. So far, it works without async calls.

Code: Pascal  [Select][+][-]
  1. (**********************************************************************************
  2.  Copyright (c) 2016 Jurassic Pork - Molly
  3.  
  4. Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. this software and associated documentation files (the "Software"), to deal in the
  6. Software without restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  8. and to permit persons to whom the Software is furnished to do so, subject to the
  9. following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  14. PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  15. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  16. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  17. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. ***********************************************************************************)
  19. unit Utilwmi;
  20.  
  21. // 0.1  Jurassic Pork Juillet 2015
  22. // 0.2  Molly  Janvier 2016 : improvement : fpc 3.0 compatibility + usage of  TFPObjectList
  23.  
  24. // Changes 2016-jan-02 (Mol)
  25. // - updated/corrected comments
  26. // - Introduction of variable nrValue.
  27. // - Generic solution for variable nr, using nrValue (inc. pointer assignment)
  28. // - re-introduction of calling ShowMessage() when exception occurs (code only
  29. //   active when USE_DIALOG is defined) + reorganized defines
  30.  
  31. // 0.3  Molly  November 2016 : improvement : support for variant arrays
  32. // Changes 2016-nov-11 (Mol)
  33. // - Add support for variant arrays
  34.  
  35. {$MODE OBJFPC}{$H+}{$HINTS ON}
  36.  
  37. {$IF FPC_FULLVERSION > 29999}  // FPC > 2.9.9
  38.   {$INFO "Use new WMI"}
  39. {$ELSE}
  40.   {$INFO "Use old WMI"}
  41.   {$DEFINE USE_OLD_WMI}
  42. {$ENDIF}
  43.  
  44. // Enable this define if wanting to use ShowMessage() to inform about an
  45. // exception.
  46. // Please realize that using unit Dialogs can 'clash', as both Freevision and
  47. // lazarus have a unit with the same name.
  48. //{$DEFINE USE_DIALOG}
  49.  
  50.  
  51. interface
  52.  
  53. uses
  54.   Classes,
  55.   contnrs;
  56.  
  57.  
  58. function GetWMIInfo(const WMIClass: string; const WMIPropertyNames: Array of String; const Condition: string = ''; Attempts: integer=1; RetryInterval: Integer= 1000): TFPObjectList;
  59.  
  60.  
  61. implementation
  62.  
  63. Uses
  64.   {$IFDEF USE_DIALOG}
  65.   Dialogs,
  66.   {$ENDIF}
  67.   Variants,
  68.   ActiveX,
  69.   ComObj,
  70.   SysUtils;
  71.  
  72. function VarArrayToStr(Value: Variant): String;
  73. var
  74.   i : Integer;
  75. begin
  76.   Result := '[';
  77.   for i := VarArrayLowBound(Value, 1) to VarArrayHighBound(Value, 1) do
  78.   begin
  79.     if Result <> '[' then Result := Result + ',';
  80.     if not VarIsNull(Value[i]) then
  81.     begin
  82.       if VarIsArray(Value[i])
  83.       then Result := Result + VarArrayToStr(Value[i])
  84.       else Result := Result + VartoStr(Value[i])
  85.     end
  86.     else Result := Result + '<null>';
  87.   end;
  88.   Result := Result + ']';
  89. end;
  90.  
  91. function GetobjWMIService(Attempts: integer = 1; RetryInterval: Integer = 1000): variant;
  92. var
  93.   FSWbemLocator : variant;
  94.   i: integer;
  95.   success: boolean = false;
  96. begin
  97.   for i:= 1 to Attempts do
  98.   begin
  99.     try
  100.       FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  101.       Result := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', ''); //Executing this line might take a few seconds!
  102.       success := true;
  103.     except
  104.       Sleep(RetryInterval);
  105.     end;
  106.     if success then Break;
  107.   end;
  108. end;
  109.  
  110. function GetWMIInfo(const WMIClass: string; const WMIPropertyNames: Array of String; const Condition: string = ''; Attempts: integer=1; RetryInterval: Integer= 1000): TFPObjectList;
  111. const
  112.   wbemFlagForwardOnly = $00000020;
  113. var
  114.   objWMIService : Variant;
  115.   colWMI        : Variant;
  116.   oEnumWMI      : IEnumvariant;
  117.   nrValue       : LongWord;
  118.   {$IFDEF USE_OLD_WMI}
  119.   objWMI        : Variant;                     // FPC < 3.0 requires WMIobj to be an variant, not an OleVariant
  120.   nr            : PLongWord;                   // FPC < 3.0 requires IEnumvariant.next to supply a pointer to a longword for # returned values
  121.   {$ELSE}
  122.   objWMI        : OLEVariant;                  // FPC 3.0 requires WMIobj to be an olevariant, not a variant
  123.   nr            : LongWord absolute nrValue;   // FPC 3.0 requires IEnumvariant.next to supply a longword variable for # returned values
  124.   {$ENDIF}
  125.   WMIproperties : String;
  126.   WMIProp       : TStringList;
  127.   Request       : String;
  128.   PropertyName  : String;
  129.   PropertyStrVal: String;
  130.   i             : integer;
  131. begin
  132.   {$IFDEF USE_OLD_WMI}
  133.   nr := @nrValue;
  134.   {$ENDIF}
  135.   // Prepare the search query
  136.   WMIProperties := '';
  137.   for i := low(WMIPropertyNames) to High(WMIPropertyNames)
  138.     do WMIProperties := WMIProperties + WMIPropertyNames[i] + ',';
  139.   Delete(WMIProperties, length(WMIProperties), 1);
  140.   // Let FPObjectList take care of freeing the objects
  141.   Result:= TFPObjectList.Create(True);
  142.   try
  143.     objWMIService := GetobjWMIService(Attempts, RetryInterval);
  144.     if Condition = ''
  145.       then Request := Format('SELECT %s FROM %s'   , [WMIProperties, WMIClass])
  146.       else Request := Format('SELECT %s FROM %s %s', [WMIProperties, WMIClass, Condition]);
  147.     // Start Request
  148.     colWMI   := objWMIService.ExecQuery(WideString(Request), 'WQL', wbemFlagForwardOnly);
  149.     // Enum for requested results
  150.     oEnumWMI := IUnknown(colWMI._NewEnum) as IEnumVariant;
  151.     // Enumerate results from query, one by one
  152.     while oEnumWMI.Next(1, objWMI, nr) = 0 do
  153.     begin
  154.       // Store all property name/value pairs for this enum to TStringList.
  155.       WMIprop := TStringList.Create;
  156.       for i := low(WMIPropertyNames) to High(WMIPropertyNames) do
  157.       begin
  158.         PropertyName := WMIPropertyNames[i];
  159.         If not VarIsNull(objWMI.Properties_.Item(WideString(PropertyName)).value) then
  160.         begin
  161.             if VarIsArray(objWMI.Properties_.Item(WideString(PropertyName)).value)
  162.             then PropertyStrVal := VarArrayToStr(objWMI.Properties_.Item(WideString(PropertyName)).value)
  163.             else PropertyStrVal := VartoStr(objWMI.Properties_.Item(WideString(PropertyName)).value)
  164.         end
  165.         else PropertyStrVal := '<null>';
  166.         WMIProp.Add(PropertyName + '=' + PropertyStrVal);
  167.       end; //for i
  168.       // Add properties from this enum to FPObjectList as TStringList
  169.       Result.Add(WMIProp);
  170.     end; //while
  171.    except
  172.     {$IFDEF USE_DIALOG}
  173.     on e: Exception do
  174.        ShowMessage('Error WMI with ' + Request + #13#10 + 'Error : ' + e.Message);
  175.     {$ELSE}
  176.       // Replace Raise with more appropiate exception if wanted.
  177.       on e: Exception do Raise;
  178.     {$ENDIF}
  179.   end; //try
  180. end;
  181.  
  182. end.
Лазар 4,4 32 bit (sometimes 64 bit); FPC3,2,2

 

TinyPortal © 2005-2018