insight/src/Agent/Insight.Agent/Internals/Extensions.cs
Kevin Kai Berthold 1e05d4576d syntax updates
2023-09-22 22:16:56 +02:00

68 lines
No EOL
1.8 KiB
C#

using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent;
public static class ManagmentExtensions
{
[SupportedOSPlatform("windows")]
public static HashSet<string> GetPropertyHashes(this ManagementBaseObject @object)
{
var properties = new HashSet<string>();
foreach (var property in @object.Properties)
{
properties.Add(property.Name);
}
return properties;
}
[SupportedOSPlatform("windows")]
internal static bool TryGet(this ManagementObjectSearcher searcher, out ManagementObjectCollection collection)
{
collection = searcher.Get();
try
{
_ = collection.Count;
return true;
}
catch (ManagementException)
{
collection.Dispose();
return false;
}
}
[SupportedOSPlatform("windows")]
internal static T? GetValue<T>(this ManagementObject @object, HashSet<string> properties, string key)
{
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return default;
if (@object[key] is not T obj)
{
return default;
}
return obj;
}
[SupportedOSPlatform("windows")]
internal static bool TryGetValue<T>(this ManagementBaseObject @object, HashSet<string> properties, string key, out T? value)
{
value = default;
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return false;
if (@object[key] is not T obj)
{
return false;
}
value = obj;
return true;
}
}