Skip to content

Commit

Permalink
Add wmi util
Browse files Browse the repository at this point in the history
  • Loading branch information
KonstantinTyukalov committed Sep 19, 2024
1 parent 6b8de4d commit c499c39
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/Agent.Sdk/Util/WmiUtil.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

using System.Management;
using System.Runtime.Versioning;

namespace Agent.Sdk.Util;

[SupportedOSPlatform("windows")]
public class WmiUtil
{
public static Task<List<ManagementBaseObject>> QueryGet(string query, CancellationToken cancellationToken)
{
var output = new List<ManagementBaseObject>();
var comletetionSource = new TaskCompletionSource<List<ManagementBaseObject>>();

var observer = new ManagementOperationObserver();
observer.ObjectReady += (sender, obj) =>
{
output.Add(obj.NewObject);
};
observer.Completed += (sender, e) =>
{
switch (e.Status)
{
case ManagementStatus.CallCanceled:
comletetionSource.SetCanceled(cancellationToken);
break;
case ManagementStatus.NoError:
comletetionSource.SetResult(output);
break;
default:
comletetionSource.SetException(new Exception($"WMI Get Query failed with status {e.Status}"));
break;
}
};

cancellationToken.Register(() =>
{
observer.Cancel();
});

using var searcher = new ManagementObjectSearcher(query);
searcher.Get(observer);

return comletetionSource.Task;
}
}

0 comments on commit c499c39

Please sign in to comment.