Skip to content

Instantly share code, notes, and snippets.

@juner
Created May 9, 2018 02:20
Show Gist options
  • Save juner/4f707a3087dbc67d3c0ed24f287699af to your computer and use it in GitHub Desktop.
Save juner/4f707a3087dbc67d3c0ed24f287699af to your computer and use it in GitHub Desktop.
Win32_Group の Administratos から Associators of を使わずに Win32_UserAccount を取得する……のをワンライナーで。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
namespace ManagementObjectSample
{
class Program
{
static void Main(string[] args)
{
foreach (var mo in
// Administrators の取得用 searcherの生成
new ManagementObjectSearcher("root/cimv2", "SELECT * FROM Win32_Group WHERE Name='Administrators'", new EnumerationOptions()).Using()
// Win32_Group の取得回り using他
.SelectMany(_mo => _mo.Get().Using().SelectMany(__mo => __mo.Cast<ManagementObject>())).Using()
// いわゆる Associators of で 関連付いた Win32_UserAccount の取得 と collection の using
.Select(_mo => _mo.GetRelated("Win32_UserAccount")).Using()
// キャストと using
.SelectMany(_mo => _mo.Cast<ManagementObject>()).Using())
Console.WriteLine($"ClassPath:{mo.ClassPath} Name:{mo.Properties["Name"]?.Value}");
Console.ReadLine();
}
}
static class DisposableExtensions
{
public static IEnumerable<T> Using<T>(this T value) where T : IDisposable
{
using (value)
yield return value;
}
public static IEnumerable<T> Using<T>(this IEnumerable<T> source) where T : IDisposable
{
foreach (var value in source)
using (value)
yield return value;
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment