いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

動いていないデバイスをリストアップする (CodeProject, How to Get a List of Non-Working Devices)


面白そうな記事だったので、メモメモ。
ネタ元は、CodeProjectです。


WMIを利用するんですね〜。勉強になります。



追記)CodeProjectにあるサンプルはVBで記述されていたので同じような内容でC#で書いてみました。

using System;
using System.Linq;
using System.Management;

namespace ShowNotWorkingDevices {

    class Program {

        static void Main(string[] args) {

            (new Program()).Execute();

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

        private void Execute() {
            //
            // 動作していないデバイスをリストアップ.
            //
            var wmi   = new ManagementObjectSearcher("SELECT * FROM Win32_PnpEntity WHERE ConfigManagerErrorCode <> 0");                        
            var query = from mo in wmi.Get().Cast<ManagementObject>()
                        let description = mo["Description"]
                        where !string.IsNullOrEmpty(description as string)
                        select mo;

            foreach (var notWorkingDevice in query) {
                Console.WriteLine("Description={0}, ErrorCode={1}", notWorkingDevice["Description"], notWorkingDevice["ConfigManagerErrorCode"]);
            }
        }

    }

}