Skip to content

Commit cf37f00

Browse files
author
Konstantin Tyukalov
committed
Add wmi util
1 parent 6b8de4d commit cf37f00

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/Agent.Sdk/Util/WmiUtil.cs

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+

2+
using System.Management;
3+
using System.Runtime.Versioning;
4+
5+
namespace Agent.Sdk.Util;
6+
7+
[SupportedOSPlatform("windows")]
8+
public class WmiUtil
9+
{
10+
public static Task<List<ManagementBaseObject>> QueryGet(string query, CancellationToken cancellationToken)
11+
{
12+
var output = new List<ManagementBaseObject>();
13+
var completionSource = new TaskCompletionSource<List<ManagementBaseObject>>();
14+
15+
var observer = new ManagementOperationObserver();
16+
observer.ObjectReady += (sender, obj) =>
17+
{
18+
output.Add(obj.NewObject);
19+
};
20+
observer.Completed += (sender, e) =>
21+
{
22+
switch (e.Status)
23+
{
24+
case ManagementStatus.CallCanceled:
25+
completionSource.SetCanceled(cancellationToken);
26+
break;
27+
28+
case ManagementStatus.NoError:
29+
completionSource.SetResult(output);
30+
break;
31+
32+
default:
33+
completionSource.SetException(new Exception($"WMI Get Query failed with status {e.Status}"));
34+
break;
35+
}
36+
};
37+
38+
cancellationToken.Register(() =>
39+
{
40+
observer.Cancel();
41+
});
42+
43+
using var searcher = new ManagementObjectSearcher(query);
44+
searcher.Get(observer);
45+
46+
return completionSource.Task;
47+
}
48+
}

0 commit comments

Comments
 (0)