Microsoft MVP성태의 닷넷 이야기
Windows: 160. WMI 쿼리를 명령행에서 간단하게 수행하는 wmic.exe [링크 복사], [링크+제목 복사]
조회: 15143
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

WMI 쿼리를 명령행에서 간단하게 수행하는 wmic.exe

그전에도 그냥 기계적으로 사용했다가 이번에 사용하면서 눈에 들어오더군요. ^^;

Useful WMI(C) commands
; http://virot.eu/useful-wmic-commands/

그러니까 말 그대로 WMI 쿼리를 명령행에서 쉽게 사용할 수 있도록 도와주는 프로그램입니다. 예를 들어, WMI Provider 중에 Win32_ComputerSystem 클래스의 경우,

Win32_ComputerSystem class
; https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-computersystem

[Dynamic, Provider("CIMWin32"), SupportsUpdate, UUID("{8502C4B0-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
class Win32_ComputerSystem : CIM_UnitaryComputerSystem
{
  uint16   AdminPasswordStatus;
  boolean  AutomaticManagedPagefile;
  boolean  AutomaticResetBootOption;
  boolean  AutomaticResetCapability;
  uint16   BootOptionOnLimit;
  uint16   BootOptionOnWatchDog;
  ...[생략]...
  boolean  HypervisorPresent;
  ...[생략]...
  string   Status;
  string   SupportContactDescription[];
  string   SystemFamily;
  string   SystemSKUNumber;
  uint16   SystemStartupDelay;
  string   SystemStartupOptions[];
  uint8    SystemStartupSetting;
  string   SystemType;
  uint16   ThermalState;
  uint64   TotalPhysicalMemory;
  string   UserName;
  uint16   WakeUpType;
  string   Workgroup;
};

제공하는 값들 중에 HypervisorPresent 속성을 구하려면 (C#에서) 다음과 같은 식의 WMI 쿼리를 작성해야 합니다.

// http://wutils.com/wmi/root/cimv2/win32_computersystem/cs-samples.html

ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");

ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem Where Name=\"" + Environment.MachineName + "\"");
    
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    
ManagementObjectCollection queryCollection = searcher.Get();
    
foreach (ManagementObject m in queryCollection) 
{
    Console.WriteLine("HypervisorPresent : {0}", m["HypervisorPresent"]);
}

저 값 하나 보자고 C# 코딩까지 하기에는 좀 그렇죠. ^^ 그래서 (운영체제에 기본 포함된) wmic.exe를 사용하면 "Win32_" 접미사를 떼고 다음과 같이 간단하게 호출할 수 있습니다.

C:\temp> wmic ComputerSystem get HypervisorPresent
HypervisorPresent
TRUE

C:\temp> 

어떤 쿼리를 지원하는지에 대해서는 wmic 도움말(/?)에 보면 다음과 같이 목록을 확인할 수 있습니다.

ALIAS                    - Access to the aliases available on the local system
BASEBOARD                - Base board (also known as a motherboard or system board) management.
BIOS                     - Basic input/output services (BIOS) management.
BOOTCONFIG               - Boot configuration management.
CDROM                    - CD-ROM management.
COMPUTERSYSTEM           - Computer system management.
CPU                      - CPU management.
CSPRODUCT                - Computer system product information from SMBIOS.
DATAFILE                 - DataFile Management.
DCOMAPP                  - DCOM Application management.
DESKTOP                  - User's Desktop management.
DESKTOPMONITOR           - Desktop Monitor management.
DEVICEMEMORYADDRESS      - Device memory addresses management.
DISKDRIVE                - Physical disk drive management.
DISKQUOTA                - Disk space usage for NTFS volumes.
DMACHANNEL               - Direct memory access (DMA) channel management.
ENVIRONMENT              - System environment settings management.
FSDIR                    - Filesystem directory entry management.
GROUP                    - Group account management.
IDECONTROLLER            - IDE Controller management.
IRQ                      - Interrupt request line (IRQ) management.
JOB                      - Provides  access to the jobs scheduled using the schedule service.
LOADORDER                - Management of system services that define execution dependencies.
LOGICALDISK              - Local storage device management.
LOGON                    - LOGON Sessions.
MEMCACHE                 - Cache memory management.
MEMORYCHIP               - Memory chip information.
MEMPHYSICAL              - Computer system's physical memory management.
NETCLIENT                - Network Client management.
NETLOGIN                 - Network login information (of a particular user) management.
NETPROTOCOL              - Protocols (and their network characteristics) management.
NETUSE                   - Active network connection management.
NIC                      - Network Interface Controller (NIC) management.
NICCONFIG                - Network adapter management.
NTDOMAIN                 - NT Domain management.
NTEVENT                  - Entries in the NT Event Log.
NTEVENTLOG               - NT eventlog file management.
ONBOARDDEVICE            - Management of common adapter devices built into the motherboard (system board).
OS                       - Installed Operating System/s management.
PAGEFILE                 - Virtual memory file swapping management.
PAGEFILESET              - Page file settings management.
PARTITION                - Management of partitioned areas of a physical disk.
PORT                     - I/O port management.
PORTCONNECTOR            - Physical connection ports management.
PRINTER                  - Printer device management.
PRINTERCONFIG            - Printer device configuration management.
PRINTJOB                 - Print job management.
PROCESS                  - Process management.
PRODUCT                  - Installation package task management.
QFE                      - Quick Fix Engineering.
QUOTASETTING             - Setting information for disk quotas on a volume.
RDACCOUNT                - Remote Desktop connection permission management.
RDNIC                    - Remote Desktop connection management on a specific network adapter.
RDPERMISSIONS            - Permissions to a specific Remote Desktop connection.
RDTOGGLE                 - Turning Remote Desktop listener on or off remotely.
RECOVEROS                - Information that will be gathered from memory when the operating system fails.
REGISTRY                 - Computer system registry management.
SCSICONTROLLER           - SCSI Controller management.
SERVER                   - Server information management.
SERVICE                  - Service application management.
SHADOWCOPY               - Shadow copy management.
SHADOWSTORAGE            - Shadow copy storage area management.
SHARE                    - Shared resource management.
SOFTWAREELEMENT          - Management of the  elements of a software product installed on a system.
SOFTWAREFEATURE          - Management of software product subsets of SoftwareElement.
SOUNDDEV                 - Sound Device management.
STARTUP                  - Management of commands that run automatically when users log onto the computer system.
SYSACCOUNT               - System account management.
SYSDRIVER                - Management of the system driver for a base service.
SYSTEMENCLOSURE          - Physical system enclosure management.
SYSTEMSLOT               - Management of physical connection points including ports,  slots and peripherals, and proprietary connections points.
TAPEDRIVE                - Tape drive management.
TEMPERATURE              - Data management of a temperature sensor (electronic thermometer).
TIMEZONE                 - Time zone data management.
UPS                      - Uninterruptible power supply (UPS) management.
USERACCOUNT              - User account management.
VOLTAGE                  - Voltage sensor (electronic voltmeter) data management.
VOLUME                   - Local storage volume management.
VOLUMEQUOTASETTING       - Associates the disk quota setting with a specific disk volume.
VOLUMEUSERQUOTA          - Per user storage volume quota management.
WMISET                   - WMI service operational parameters management.

위의 내용을 보면, "wmic ComputerSystem ..."에서의 "ComputerSystem"은 "Win32_ComputerSystem"에서 "Win32_"를 떼어냈다기보다는 그냥 별칭으로 정의된 것에 불과한 것임을 알 수 있습니다.

그런데, 저 목록에 없는 경우는 퀴리를 못하는 걸까요? 예를 들어, 지난 글에 다룬,

C# - Open Hardware Monitor를 이용한 CPU 온도 정보
; https://www.sysnet.pe.kr/2/0/11904

"root\WMI" 네임스페이스에 속한 "MSAcpi_ThermalZoneTemperature" 클래스의 경우 저 목록에 없습니다. 괜찮습니다. ^^ 다음과 같이 직접 네임스페이스와 "path" 인자의 도움으로 간단하게 해결이 됩니다.

C:\Windows\System32>wmic /NAMESPACE:\\root\WMI path MSAcpi_ThermalZoneTemperature get CurrentTemperature
CurrentTemperature
3010
3030

윈도우 10부터 "WMIC is deprecated"라는 문구가 뜨는 걸로 봐서 더 이상 지원이 안 될 듯싶은데 어쨌든 현재 상황에서 유용하게 시스템 조회를 할 수 있는 하나의 도구임에는 분명합니다.




참고로, 아래의 쿼리들도 한번 봐 두면 좋겠죠! ^^

A Brief Usage Guide for Wmic
; https://www.xorrior.com/wmic-the-enterprise/

Host Enumeration:

    --- OS Specifics ---
    wmic os LIST Full (* To obtain the OS Name, use the "caption" property)
    wmic computersystem LIST full

    --- Anti-Virus ---
    wmic /namespace:\\root\securitycenter2 path antivirusproduct

    --- Peripherals ---
    wmic path Win32_PnPdevice 

    --- Installed Updates ---
    wmic gfe list brief

    --- Directory Listing and File Search ---
    wmic DATAFILE where "path='\\Users\\test\\Documents\\'" GET Name,readable,size
    wmic DATAFILE where "drive='C:' AND Name like '%password%'" GET Name,readable,size /VALUE

    --- Local User Accounts ---
    wmic USERACCOUNT Get Domain,Name,Sid

Domain Enumeration:

    --- Domain and DC Info ---
    wmic NTDOMAIN GET DomainControllerAddress,DomainName,Roles /VALUE

    --- Domain User Info ---
    wmic /NAMESPACE:\\root\directory\ldap PATH ds_user where "ds_samaccountname='testAccount'" GET 

    --- List All Users ---
    wmic /NAMESPACE:\\root\directory\ldap PATH ds_user GET ds_samaccountname

    --- List All Groups ---
    wmic /NAMESPACE:\\root\directory\ldap PATH ds_group GET ds_samaccountname

    --- Members of A Group ---
    wmic /NAMESPACE:\\root\directory\ldap PATH ds_group where "ds_samaccountname='Domain Admins'" Get ds_member /Value

    --- List All Computers ---
    wmic /NAMESPACE:\\root\directory\ldap PATH ds_computer GET ds_samaccountname
    OR
    wmic /NAMESPACE:\\root\directory\ldap PATH ds_computer GET ds_dnshostname

Misc:

    --- Execute Remote Command ---
    wmic process call create "cmd.exe /c calc.exe"
    OR
    wmic /node:server1 process call create "win32calc.exe"

    --- Enable Remote Desktop ---
    wmic rdtoggle where AllowTSConnections="0" call SetAllowTSConnections "1"
    OR
    wmic /node:remotehost path Win32_TerminalServiceSetting where AllowTSConnections="0" call SetAllowTSConnections "1"

Find partition letters on physical drives using wmic
; https://superuser.com/questions/634842/find-partition-letters-on-physical-drives-using-wmic

    --- how to get primary harddisk serial number only ---
    wmic logicaldisk where (DeviceID="C:") assoc /assocclass:Win32_LogicalDiskToPartition
    wmic partition where (DeviceID="Disk #0, Partition #0") assoc /assocclass:Win32_DiskDriveToDiskPartition
    wmic path win32_diskdrive where deviceid='\\\\.\\PHYSICALDRIVE0' get serialnumber




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/25/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2019-07-08 09시10분
ex) wmic /NAMESPACE:\\root\cimv2 path SoftwareLicensingProduct WHERE (ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f' AND LicenseStatus=1) get *
정성태
2022-10-30 11시31분
파이썬에 wmi를 지원하는 패키지가 있군요. ^^ 이것을 이용하면 다음과 같이 값을 가져올 수 있습니다.

# pip install wmi

import wmi
data = wmi.WMI()

result = data.Win32_ComputerSystem()
print(type(result)) # <class 'list'>

print(result[0].HypervisorPresent) # True
정성태

... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
12970정성태2/15/20227818.NET Framework: 1156. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 h264 형식의 파일로 쓰기 [1]파일 다운로드1
12969정성태2/14/20226450개발 환경 구성: 638. Visual Studio의 Connection Manager 기능(Remote SSH 관리)을 위한 명령행 도구 - 두 번째 이야기파일 다운로드1
12968정성태2/14/20226610오류 유형: 794. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for '...'.
12967정성태2/14/20226992VC++: 153. Visual C++ - C99 표준의 Compund Literals 빌드 방법 [4]
12966정성태2/13/20226857.NET Framework: 1155. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 yuv420p + rawvideo 형식의 파일로 쓰기파일 다운로드1
12965정성태2/13/20226723.NET Framework: 1154. "Hanja Hangul Project v1.01 (파이썬)"의 C# 버전
12964정성태2/11/20227035.NET Framework: 1153. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 avio_reading.c 예제 포팅파일 다운로드1
12963정성태2/11/20227793.NET Framework: 1152. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 (저해상도 현상 해결)파일 다운로드1
12962정성태2/9/20227636오류 유형: 793. 마이크로소프트 스토어 - 제품이 존재하지 않습니다. 재고가 없는 것일 수 있습니다.
12961정성태2/8/20227765.NET Framework: 1151. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 프레임의 크기 및 포맷 변경 예제(scaling_video.c) [7]파일 다운로드1
12960정성태2/8/20227189개발 환경 구성: 637. ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 세 번째 이야기
12959정성태2/7/20227891.NET Framework: 1150. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 두 번째 이야기 [2]파일 다운로드1
12958정성태2/6/20227962.NET Framework: 1149. C# - ffmpeg(FFmpeg.AutoGen) - 비디오 프레임 디코딩 [2]파일 다운로드1
12957정성태2/6/20227580개발 환경 구성: 636. ffmpeg.exe를 이용해 planar 포맷의 데이터를 packed 형식으로 변환하는 방법? [2]
12956정성태2/4/20226788.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen) - decoding 과정 [2]파일 다운로드1
12955정성태2/4/20226181개발 환경 구성: 635. 비주얼 스튜디오에서 실행하던 ASP.NET Core (.NET Framework) 응용 프로그램을 명령행에서 실행하는 방법 (2)
12954정성태2/4/20226041VS.NET IDE: 173. 비주얼 스튜디오 - Output 창에 색상이 지정된 출력 결과가 "[39m[22m" 식의 문자로 나오는 문제
12953정성태2/2/20226298Linux: 48. Windows 11 + WSL 우분투 GUI 환경에서 한글 출력
12952정성태2/2/20226777.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터 예제(filter_audio.c)파일 다운로드1
12951정성태2/2/20226737.NET Framework: 1147. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터링 예제(filtering_audio.c)파일 다운로드1
12950정성태2/1/20226380.NET Framework: 1146. .NET 6에 추가되지 않은 Generic Math (예: INumber<T>)
12949정성태2/1/20226222.NET Framework: 1145. C# - ffmpeg(FFmpeg.AutoGen) - Codec 정보 열람 및 사용 준비파일 다운로드1
12948정성태1/30/20226349.NET Framework: 1144. C# - ffmpeg(FFmpeg.AutoGen) AVFormatContext를 이용해 ffprobe처럼 정보 출력파일 다운로드1
12947정성태1/30/20227497개발 환경 구성: 634. ffmpeg.exe - 기존 동영상 컨테이너에 다중 스트림을 추가하는 방법
12946정성태1/28/20226024오류 유형: 792. .NET Core - 로컬 개발 중에 docker 호스팅으로 바꾸는 경우 SQL 서버 접근 방법
12945정성태1/28/20226263오류 유형: 791. SQL 서버 로그인 시 localhost는 되고, 127.0.0.1로는 안 되는 문제
... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...