Очень часто для написания скриптов или фильтров требуется использовать WMI запросы. Я приведу те, которые встречаются чаще всего. В Windows есть встроенная утилита WMIC, которой можно выполнять запросы. Существует также язык WQL Query, который позволяет делать аналогичные запросы в различных системах, таких как SCCM.

Немного теории. Для выполнения запросов, необходимо знать, в каком адресом пространстве (namespace) лежит необходимый вам класс. Если вы не указываете namespace, то по умолчанию используется ROOT\cli и ROOT\cimv2. Например, у меня на компьютере cimv2 в себя включает 504 класса, каждый из которых имеет набор свойств (Properties) и методов (Methods). Например, системный класс Win32_ComputerSystem имеет 64 свойства и 4 метода.

Общий систаксис команды таков: wmic /namespace:\\root\<namespace> path <class name>  get <attributes>

В комманде вы указываете или путь к зарегистрированному классу, или его алиас. Аласы есть не для всех классов. Список достпных алиасов можно получить по команде: wmic /?. Остальные пути (path) можно узнать, скачав и запустив утилиту WMI Explorer:

Класс Win32_ComputerSystem

Вы можете написать как полный путь wmic path Win32_computersystem get model, так и используя alias wmic computersystem get model, эти записи равноценны.

На языке WQL запрос будет выглядеть так:

SELECT * FROM Win32_ComputerSystem WHERE Name='pc_name'

При написании скриптов на Powershell следует использовать команделт Get-WmiObject:

1
2
3
4
5
6
7
8
9
10
11
$computer = $env:COMPUTERNAME
$namespace = "ROOT\cimv2"
$classname = "Win32_ComputerSystem"
 
Write-Output "====================================="
Write-Output "COMPUTER : $computer "
Write-Output "CLASS : $classname "
Write-Output "====================================="
 
Get-WmiObject -Class $classname -ComputerName $computer -Namespace $namespace |
Select-Object * -ExcludeProperty PSComputerName, Scope, Path, Options, ClassPath, Properties, SystemProperties, Qualifiers, Site, Container | Format-List -Property [a-z]*

Вы можете писать и более сложные запросы, используя условие Where:

WMIC Path Win32_NetworkAdapter Where ( Manufacturer = "Realtek" And PhysicalAdapter = TRUE ) Get ...

Вы можете вывести не одно, а несколько значений свойств сразу. Тогда они будут выводиться в виде таблицы со столбцами:

wmic environment get name, variablevalue

или все свойства, исользуя маску *:

wmic path win32_bios get *

Наиболее полезные WMI запросы

  • Версия BIOS: wmic path win32_bios get biosversion, releasedate
  • Производитель платы и SKU системы: wmic baseboard get product,manufacturer
  • Модель компьютера (не работает на платах производства Intel): wmic computersystem get model
  • Производитель платы (может не совпадать с информаций в класе BIOS): wmic computersystem get manufacturer
  • Тип шасси: wmic /namespace:\\root\cimv2 path Win32_SystemEnclosure get ChassisTypes
  • Информация о диске: wmic diskdrive get model,name,size
  • Получить версию Intel Management Engine firmware (ME): wmic /namespace:\\root\Intel_ME path ME_System get FWVersion
  • Список периферийных устройств: wmic path Win32_PnPdevice
  • Список процессов на указанном PC (включая удаленный): wmic /node:computername get name, processid
  • Список и состояние принтеров на указанном PC: wmic /node:hostname printer list status
  • Конфигурация принтеров: wmic printerconfig
  • Информация об операционной системе с выводом в HTML файл: wmic os get bootdevice, buildnumber, caption, freespaceinpagingfiles, installdate, name, systemdrive, windowsdirectory /format:htable > c:\osinfo.htm
  • Username залогиненного пользователя: wmic /node:(computername or ip address) computersystem get username
  • Список серверов на удаленной машине: wmic /node:remotehost service list brief
  • Список всех установленных программ: wmic product get name
  • Архитектура компьютера: wmic computersystem get systemtype
  • Название операционной системы: wmic os get name
  • Список установленных апдейтов: wmic qfe get description,installedOn,Hotfixid
  • Получить Hardware ID видеокарты: wmic PATH Win32_videocontroller GET pnpdeviceid
  • Список программ в автозагрузке: wmic startup get caption,command
  • Получить версию файла (обратите внимание на двойной \\ в пути к файлу): wmic datafile where name=»C:\\Windows\\notepad.exe» get version
  • Список локальных пользоваелей: wmic USERACCOUNT Get Domain,Name,Sid
  • Выполнить команду в удаленной консоли (без psexec!): wmic process call create «cmd.exe /c calc.exe»
  • Прибить процесс: wmic process where name=»iexplore.exe» call terminate

Таблица алиасов для основных классов и свойства ими возвращаемые

baseboard get Manufacturer, Model, Name, PartNumber, slotlayout, serialnumber, poweredon
bios get name, version, serialnumber
bootconfig get BootDirectory, Caption, TempDirectory, Lastdrive
cdrom get Name, Drive, Volumename
computersystem get Name, domain, Manufacturer, Model, NumberofProcessors, PrimaryOwnerName,Username, Roles, totalphysicalmemory /format:list
cpu get Name, Caption, MaxClockSpeed, DeviceID, status
datafile where name=’c:\\boot.ini’ get Archive, FileSize, FileType, InstallDate, Readable, Writeable, System, Version
dcomapp get Name, AppID /format:list
desktop get Name, ScreenSaverExecutable, ScreenSaverActive, Wallpaper /format:list
desktopmonitor get screenheight, screenwidth
diskdrive get Name, Manufacturer, Model, InterfaceType, MediaLoaded, MediaType
diskquota get User, Warninglimit, DiskSpaceUsed, QuotaVolume
environment get Description, VariableValue
fsdir where name=’c:\\windows’ get Archive, CreationDate, LastModified, Readable, Writeable, System, Hidden, Status
group get Caption, InstallDate, LocalAccount, Domain, SID, Status
idecontroller get Name, Manufacturer, DeviceID, Status
irq get Name, Status
job get Name, Owner, DaysOfMonth, DaysOfWeek, ElapsedTime, JobStatus, StartTime, Status
loadorder get Name, DriverEnabled, GroupOrder, Status
logicaldisk get Name, Compressed, Description, DriveType, FileSystem, FreeSpace, SupportsDiskQuotas, VolumeDirty, VolumeName
memcache get Name, BlockSize, Purpose, MaxCacheSize, Status
memlogical get AvailableVirtualMemory, TotalPageFileSpace, TotalPhysicalMemory, TotalVirtualMemory
memphysical get Manufacturer, Model, SerialNumber, MaxCapacity, MemoryDevices
netclient get Caption, Name, Manufacturer, Status
netlogin get Name, Fullname, ScriptPath, Profile, UserID, NumberOfLogons, PasswordAge, LogonServer, HomeDirectory, PrimaryGroupID
netprotocol get Caption, Description, GuaranteesSequencing, SupportsBroadcasting, SupportsEncryption, Status
netuse get Caption, DisplayType, LocalName, Name, ProviderName, Status
nic get AdapterType, AutoSense, Name, Installed, MACAddress, PNPDeviceID,PowerManagementSupported, Speed, StatusInfo
nicconfig get MACAddress, DefaultIPGateway, IPAddress, IPSubnet, DNSHostName, DNSDomain
nicconfig get MACAddress, IPAddress, DHCPEnabled, DHCPLeaseExpires, DHCPLeaseObtained, DHCPServer
nicconfig get MACAddress, IPAddress, DNSHostName, DNSDomain, DNSDomainSuffixSearchOrder, DNSEnabledForWINSResolution, DNSServerSearchOrder
nicconfig get MACAddress, IPAddress, WINSPrimaryServer, WINSSecondaryServer, WINSEnableLMHostsLookup, WINSHostLookupFile
ntdomain get Caption, ClientSiteName, DomainControllerAddress, DomainControllerName, Roles, Status
ntevent where (LogFile=’system’ and SourceName=’W32Time’) get Message, TimeGenerated
ntevent where (LogFile=’system’ and SourceName=’W32Time’ and Message like ‘%timesource%’) get Message, TimeGenerated
ntevent where (LogFile=’system’ and SourceName=’W32Time’ and EventCode!=’29’) get TimeGenerated, EventCode, Message
onboarddevice get Description, DeviceType, Enabled, Status
os get Version, Caption, CountryCode, CSName, Description, InstallDate, SerialNumber, ServicePackMajorVersion, WindowsDirectory /format:list
os get CurrentTimeZone, FreePhysicalMemory, FreeVirtualMemory, LastBootUpTime, NumberofProcesses, NumberofUsers, Organization, RegisteredUser, Status
pagefile get Caption, CurrentUsage, Status, TempPageFile
pagefileset get Name, InitialSize, MaximumSize
partition get Caption, Size, PrimaryPartition, Status, Type
printer get DeviceID, DriverName, Hidden, Name, PortName, PowerManagementSupported, PrintJobDataType, VerticalResolution, Horizontalresolution
printjob get Description, Document, ElapsedTime, HostPrintQueue, JobID, JobStatus, Name, Notify, Owner, TimeSubmitted, TotalPages
process get Caption, CommandLine, Handle, HandleCount, PageFaults, PageFileUsage, PArentProcessId, ProcessId, ThreadCount
product get Description, InstallDate, Name, Vendor, Version
qfe get description, FixComments, HotFixID, InstalledBy, InstalledOn, ServicePackInEffect
quotasetting get Caption, DefaultLimit, Description, DefaultWarningLimit, SettingID, State
recoveros get AutoReboot, DebugFilePath, WriteDebugInfo, WriteToSystemLog
Registry get CurrentSize, MaximumSize, ProposedSize, Status
scsicontroller get Caption, DeviceID, Manufacturer, PNPDeviceID
server get ErrorsAccessPermissions, ErrorsGrantedAccess, ErrorsLogon, ErrorsSystem, FilesOpen, FileDirectorySearches
service get Name, Caption, State, ServiceType, StartMode, pathname
share get name, path, status
sounddev get Caption, DeviceID, PNPDeviceID, Manufacturer, status
startup get Caption, Location, Command
sysaccount get Caption, Domain, Name, SID, SIDType, Status
sysdriver get Caption, Name, PathName, ServiceType, State, Status
systemenclosure get Caption, Height, Depth, Manufacturer, Model, SMBIOSAssetTag, AudibleAlarm, SecurityStatus, SecurityBreach, PoweredOn, NumberOfPowerCords
systemslot get Number, SlotDesignation, Status, SupportsHotPlug, Version, CurrentUsage, ConnectorPinout
tapedrive get Name, Capabilities, Compression, Description, MediaType, NeedsCleaning, Status, StatusInfo
timezone get Caption, Bias, DaylightBias, DaylightName, StandardName
useraccount get AccountType, Description, Domain, Disabled, LocalAccount, Lockout, PasswordChangeable, PasswordExpires, PasswordRequired, SID
memorychip get BankLabel, Capacity, Caption, CreationClassName, DataWidth, Description, Devicelocator, FormFactor, HotSwappable, InstallDate, InterleaveDataDepth, InterleavePosition, Manufacturer, MemoryType, Model, Name, OtherIdentifyingInfo, PartNumber, PositionInRow, PoweredOn, Removable, Replaceable, SerialNumber, SKU, Speed, Status, Tag, TotalWidth, TypeDetail, Version
[Посещений: 25 405, из них сегодня: 1]

Добавить комментарий