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 cf37f00
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 completionSource = 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:
completionSource.SetCanceled(cancellationToken);
break;

case ManagementStatus.NoError:
completionSource.SetResult(output);
break;

default:
completionSource.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 completionSource.Task;
}
}

0 comments on commit cf37f00

Please sign in to comment.