diff --git a/src/Agent.Sdk/Util/WmiUtil.cs b/src/Agent.Sdk/Util/WmiUtil.cs new file mode 100644 index 0000000000..937b814f8e --- /dev/null +++ b/src/Agent.Sdk/Util/WmiUtil.cs @@ -0,0 +1,48 @@ + +using System.Management; +using System.Runtime.Versioning; + +namespace Agent.Sdk.Util; + +[SupportedOSPlatform("windows")] +public class WmiUtil +{ + public static Task> QueryGet(string query, CancellationToken cancellationToken) + { + var output = new List(); + var comletetionSource = new TaskCompletionSource>(); + + 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; + } +}