WMI: Знакомство

WMI (Windows Management Instrumentation) – это специально разработанный компанией Microsoft интерфейс управления Windows, основанный на определенных стандартах. Технология WMI широко используется системными администраторами при помощи специально написанных сценариях. Но WMI можно использовать и в приложениях C#, Visual Basic и т.д. WMI включена во все современные версии Windows, а также ее можно бесплатно загрузить с сайта Microsoft. С помощью WMI можно узнать множество информации о компьютерах. Кроме того, технология WMI позволяет работать с удаленными компьютерами, и именно, эта возможность и представляет особый интерес для программистов и системных администраторов.

Все приложения и элементы оборудования, управляемые при помощи WMI, являются управляемыми объектами (managed object). Объектом является устройство (материнская плата, видеокарта, сетевой адаптер) или программное приложение (операционная система, программа).

Функциональность WMI обеспечивается файлом WINMGMT.EXE, который запускается как служба. Когда сценарии и программы обращаются к WMI, то служба перехватывает эти вызовы и пересылает их диспетчеру объектов CIM (CIM Object Manager). Этот диспетчер является входом в инфраструктуру WMI, обеспечивая первоначальное создание объектов и обеспечивает однообразный способ доступа к управяемым объектам. Когда диспетчер получает запрос на обращение к объекту, он сначала проверяет хранилище объектов (repository). Если запрашиваемая информация не найдена в хранилище, то оно передает запрос к поставщику объекта (provider). Поставщик - это интерфейс между управляемым объектом и диспетчером CIMOM. Поставщик собирает сведения об устройстве и делает их доступными для диспетчера. Несколько поставщиков входят в состав WMI (Active Directory provider, Event Log provider и др.).

Использование WMI в сценариях

Для подключения к объекту используется функция GetObject и выполняется назначение ее значения переменной.

Set objVar = GetObject("winmgmts:[impersonationLeve = imprsonate}!\\computer\root\namespace").ExecQuery(WQL)


Moniker string

Что такое moniker string? Это некое специальное имя для обращения к объектам или классам объектов WMI. Формат этой строки фактически представляет собой разновидность URL. Все moniker string начинаются с отличительного идентификатора Winmgmts:. Эта часть moniker string является обязательной. Далее формат зависит от того, как мы хотим обращаться к объекту.

Например, вот так:

Winmgmts://servername/root/cimv2:Win32_OperatingSystem

В приведенном примере servername - это сетевое имя компьютера, на котором мы хотим получить доступ к объекту WMI. Если указать вместо сетевого имени символ "." (точка), то подключение будет происходить к локальному компьютеру. Root/CIMv2 - это пространство имен репозитория WMI. После двоеточия идет наименование класса WMI, к объектам которого мы хотим обратиться. В данном примере это класс Win32_OperatingSystem. Следует заметить, что в moniker string можно использовать не только прямую наклонную черту, но и обратную, так что строки "winmgmts://server01/root/cimv2" и "winmgmts:\\server01\root\cimv2" одинаковы.

При подключении к репозиторию WMI необязательно указывать имя локального сервера точкой. Строка может выглядеть и так: "WinMgmts:root/CIMv2". Если в строке moniker-string имя сервера не указано, то подключение произойдет к локальному репозиторию WMI. Точно так же, как и в случае использования строки "WinMgmts://./root/CIMv2".

Пространства имен WMI

Пространство имен WMI - это раздел репозитория WMI, которая призвана группировать классы и объекты WMI по назначению, а также определять атрибуты безопасности при доступе к классам и объектам в каждом таком контейнере. Все пространства имен начинаются с корня, который в WMI обозначается ключевым словом root. После имени корня через косую черту указывается пространство имен. Пространства имен могут быть вложенными. Пример того, как выглядит пространство имен: root/mynamespace/subnamespace. ROOT - это предок пространства имен для WMI, в нем содержится все дочерние пространства имен. Подавляющее большинство классов и объектов, которые интересуют вас, размещается в пространстве имен root/CIMv2.

WMI включает три дочерних пространства имен:

  • Cimv2 - хранит классы Win32
  • Default - хранит системные классы
  • Security - хранит классы безопасности WMI

Одно из существующих в Windows пространств имен WMI может быть выбрано по умолчанию. Это означает, что если вы попытаетесь подключиться к этому хосту, не указав в moniker-string необходимое пространство имен, то вы автоматически будете подключены к выбранному по умолчанию. В стандартной инсталляции Windows по умолчанию выбрано пространство имен root\cimv2.

Безопасность WMI

Если внимательно изучить схему архитектуры WMI, то легко заметить, что все взаимодействие с ядром WMI происходит с использованием интерфейсов COM+/DCOM. В свою очередь COM+ и DCOM в качестве транспортного протокола используют RPC. Эта архитектурная особенность накладывает определенный отпечаток на идеологию системы безопасности WMI. В частности, для людей, знакомых с технологиями DCOM и COM+, слова "имперсонация" и "делегирование" не новы.

Для того чтобы некая учетная запись имела возможность подключаться к репозиторию WMI, необходимо дать ей соответствующие права. Права, как вы уже могли догадаться, нужно дать как на пространство имен - WMI name space (воспользовавшись оснасткой wmimgmt.msc), так и на DCOM-приложения диспетчера WMI - CIM Object Manager (воспользовавшись оснасткой управления COM+ comexp.msc или утилитой dcomcnfg.exe). Вот минимальный список приложений DCOM, права на которые необходимы для удаленной работы с WMI: Windows Management and Instrumentation, Microsoft WMI Provider Subsystem Host. Права на другие DCOM-приложения могут понадобиться в зависимости от используемого режима имперсонации.

Имперсонация

Инструкция {ImpersonationLevel = impersonate}! заставляется WMI выполнить сценарий с личными данными лица, вызывающего сценарий. Зачем нужна имперсонация? Все довольно просто, это метод, при котором для подключения к ресурсу процесс (поток) или система должны использовать не свой контекст безопасности, а учетные данные другого субъекта безопасности. Представьте, что некая служба, запущенная в контексте безопасности LocalSystem, должна выполнить действие от лица другой учетной записи (например, от лица текущего зарегистрированного на компьютере пользователя). В этом случае ей необходимо создать специальный маркер доступа (Access Token), описывающий контекст безопасности той учетной записи, под которой мы хотим выполнить указанное действие. Безусловно, для того чтобы создать такой маркер доступа, этой службе необходимо знать учетные данные этого пользователя или, если этот процесс происходит на локальной машине, получить копию маркера доступа зарегистрированного локально пользователя (безусловно, для этого контекст безопасности службы должен обладать привилегией создания маркеров доступа). В Windows 2000 и выше имперсонацию можно не использовать.

Бывает чуть более сложный вариант имперсонации - делегирование. Этот вариант необходим тогда, когда подключение к конечному ресурсу выполняется не самим субъектом безопасности (в нашем примере - службой от лица пользователя), а через посредника (например, промежуточный сервер). Представьте ситуацию, что интернет-пользователь подключается не напрямую к базе данных, а через веб-приложение на третьем сервере. Для осуществления такого подключения веб-приложение должно получить от субъекта безопасности (нашей службы) маркер доступа с правом делегирования - это позволит веб-приложению использовать маркер доступа субъекта безопасности уже при подключении к базе данных.

В случае с WMI делегирование может выглядеть так - мы, работая на станции администратора, подключаемся по WMI к некому серверу и запускаем на нем процесс с помощью метода Execute класса Win32_Process. Теперь представим, что этот процесс есть не что иное, как другой скрипт WMI, который подключается к еще одному хосту в сети для того, чтобы сделать какие-то действия. Если мы не воспользуемся делегированием, то на конечной машине скрипт будет запущен в контексте безопасности учетной записи промежуточного сервера, что далеко не всегда желаемо. С другой стороны, подобная ситуация с делегированием в реальной жизни требуется крайне редко.

Язык запросов WQL

WMI использует язык запросов WMI Query Language (WQL), который схож с языком SQL. Основной синтаксис WQL-выражения

.ExecQuery("select propmeth from class")

Команда ExecQuery запускает WQL-выражение, расположенное в кавычках и круглых скобках. Propmeth определяет свойство или метод, извлекаемый из определенного класса class. Классы содержат свойства и методы объекта.

Кроме команды ExecQuery можно выполнять метод ExecNotificationQuery, предназначенный для обнаружения изменения экземпляра класса. Данный метод позволяет опрашивать события с указанной периодичностью и может использоваться для наблюдения за протоколом событий, процессом, памятью и т.д. с определенным интервалом.


Win32_BaseBoard

Класс Win32_BaseBoard предоставляет сведения о материнской плате.

class Win32_BaseBoard : CIM_Card
{
  string   Caption;
  string   ConfigOptions[];
  string   CreationClassName;
  real32   Depth;
  string   Description;
  real32   Height;
  boolean  HostingBoard;
  boolean  HotSwappable;
  datetime InstallDate;
  string   Manufacturer;
  string   Model;
  string   Name;
  string   OtherIdentifyingInfo;
  string   PartNumber;
  boolean  PoweredOn;
  string   Product;
  boolean  Removable;
  boolean  Replaceable;
  string   RequirementsDescription;
  boolean  RequiresDaughterBoard;
  string   SerialNumber;
  string   SKU;
  string   SlotLayout;
  boolean  SpecialRequirements;
  string   Status;
  string   Tag;
  string   Version;
  real32   Weight;
  real32   Width;
};

Методы

IsCompatible

Свойства

Caption
Data type: stringAccess type: Read-only Short description of the object—a one-line string. This property is inherited from CIM_ManagedSystemElement.

ConfigOptions
Data type: string array Access type: Read-only
Array that represents the configuration of the jumpers and switches located on the baseboard. Example: "JP2: 1-2 Cache Size is 256K, 2-3 Cache Size is 512K, SW1-1: Close to Disable On Board Video"

CreationClassName
Data type: stringAccess type: Read-onlyQualifiers: Key, MaxLen (256)
Name of the first concrete class that appears in the inheritance chain used in the creation of an instance. When used with the other key properties of the class, the property allows all instances of this class and its subclasses to be identified uniquely. This property is inherited from CIM_PhysicalElement.

Depth
Data type: real32Access type: Read-only
Depth of the physical package in inches. This property is inherited from CIM_PhysicalPackage.

Description
Data type: stringAccess type: Read-only
Description of the object. This property is inherited from CIM_ManagedSystemElement.

Height
Data type: real32Access type: Read-only
Height of the physical package—in inches. This property is inherited from CIM_PhysicalPackage.

HostingBoard
Data type: booleanAccess type: Read-only
If TRUE, the card is a motherboard, or a baseboard in a chassis. This property is inherited from CIM_Card.

HotSwappable
Data type: booleanAccess type: Read-only If TRUE, the package can be hot-swapped. A physical package can be hot-swapped if it is possible to replace the element with a physically different but equivalent element while the containing package has power applied to it—that is, while it is ON. For example, a disk drive package inserted using SCA connectors is removable and can be hot-swapped. All packages that can be hot-swapped are inherently removable and replaceable. This property is inherited from CIM_PhysicalPackage.

InstallDate
Data type: datetimeAccess type: Read-only
Date and time the object was installed. This property does not need a value to indicate that the object is installed. This property is inherited from CIM_ManagedSystemElement.

Manufacturer
Data type: stringAccess type: Read-only
Name of the organization responsible for producing the physical element. This property is inherited from CIM_PhysicalElement.

Model
Data type: stringAccess type: Read-only
Name by which the physical element is known. This property is inherited from CIM_PhysicalElement.

Name
Data type: stringAccess type: Read-only Label by which the object is known. When subclassed, the property can be overridden to be a key property. This property is inherited from CIM_ManagedSystemElement.

OtherIdentifyingInfo
Data type: stringAccess type: Read-only
Captures additional data, beyond asset tag information, that can be used to identify a physical element. One example is bar code data that is associated with an element that also has an asset tag. Note that if only bar code data is available and unique or able to be used as an element key, the property value would be NULL and the bar code data would be used as the class key, in the tag property. This property is inherited from CIM_PhysicalElement.

PartNumber
Data type: stringAccess type: Read-only
Part number assigned by the organization responsible for producing or manufacturing the physical element. This property is inherited from CIM_PhysicalElement.

PoweredOn
Data type: booleanAccess type: Read-only
If TRUE, the physical element is powered ON. This property is inherited from CIM_PhysicalElement.
Product Data type: stringAccess type: Read-only
Baseboard part number defined by the manufacturer.
Removable Data type: booleanAccess type: Read-only
If TRUE, a package is removable. A physical package is removable if it is designed to be taken in and out of the physical container in which it is normally found—without impairing the function of the overall packaging. A package can still be removable if the power must be OFF to perform the removal. If the power can be ON and the package removed, then the element is removable and can be hot-swapped. For example, an extra battery in a laptop is removable, as is a disk drive package inserted using SCA connectors. However, the latter can also be hot-swapped. A laptop's display is not removable, nor is a nonredundant power supply. Removing these components would impact the function of the overall packaging, or is impossible due to the tight integration of the package. This property is inherited from CIM_PhysicalPackage.

Replaceable
Data type: booleanAccess type: Read-only
If TRUE, a package is replaceable. A physical package is replaceable if it is possible to replace (FRU or upgrade) the element with a physically different one. For example, some computer systems allow the main processor chip to be upgraded to one of a higher clock rating. In this case, the processor is said to be replaceable. Another example is a power supply package mounted on sliding rails. All removable packages are inherently replaceable. This property is inherited from CIM_PhysicalPackage.

RequirementsDescription
Data type: stringAccess type: Read-only
Free-form string that describes the way in which this card is physically unique from other cards. The property only has meaning when the corresponding Boolean property SpecialRequirements is set to TRUE. This property is inherited from CIM_Card.
RequiresDaughterBoard Data type: booleanAccess type: Read-only
If TRUE, at least one daughterboard or auxiliary card is required to function properly. This property is inherited from CIM_Card.

SerialNumber
Data type: stringAccess type: Read-only
Manufacturer-allocated number used to identify the physical element. This property is inherited from CIM_PhysicalElement.

SKU Data type: stringAccess type: Read-only
Stock-keeping unit number for the physical element. This property is inherited from CIM_PhysicalElement.
SlotLayout Data type: stringAccess type: Read-only
Free-form string that describes the slot position, typical usage, restrictions, individual slot spacing or any other pertinent information for the slots on a card. This property is inherited from CIM_Card.
SpecialRequirements Data type: booleanAccess type: Read-only
If TRUE, this card is physically unique from other cards of the same type and therefore requires a special slot. For example, a double-wide card requires two slots. Another example is where a certain card may be used for the same general function as other cards but requires a special slot (for example, extra long), whereas the other cards can be placed in any available slot. If set to TRUE, then the corresponding property, RequirementsDescription, should specify the nature of the uniqueness or purpose of the card. This property is inherited from CIM_Card.
Status Data type: stringAccess type: Read-only
Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, yet the managed element is neither "OK" nor in one of the other states. This property is inherited from CIM_ManagedSystemElement.

The values are:
"OK""Error""Degraded""Unknown" "Starting""Pred Fail""Stopping""Service""Stressed""NonRecover""No Contact""Lost Comm"Tag Data type: stringAccess type: Read-onlyQualifiers: Key, MaxLen (256)
Unique identifier of the baseboard of the system. This property is inherited from CIM_PhysicalElement.
Example: "Base Board"
Version Data type: stringAccess type: Read-only
Version of the physical element. This property is inherited from CIM_PhysicalElement.
Weight Data type: real32Access type: Read-only
Weight of the physical package in pounds. This property is inherited from CIM_PhysicalPackage.
Width Data type: real32Access type: Read-only
Width of the physical package in inches. This property is inherited from CIM_PhysicalPackage.

Примечания

Класс Win32_BaseBoard наследует от CIM_Card, который в свою очередь наследует от CIM_PhysicalPackage.

Пример

[C#] Получить серийный номер материнской платы

// Добаввить ссылку на System.Management.
using System.Management;

private string GetMotherBoardSerialNumber()
{
    string result = null;
    string query = "SELECT * FROM Win32_BaseBoard";
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher(query);
    foreach (ManagementObject info in searcher.Get())
    {
        result = info.GetPropertyValue("SerialNumber").ToString();
    }

    return result;
}

private void butGetBoardNumber_Click(object sender, EventArgs e)
{
    txtSerialNumber.Text = GetMotherBoardSerialNumber();
}

Смотри также

Computer System Hardware Classes


Win32_BootConfiguration

Класс Win32_BootConfiguration содержит информацию о загрузочной конфигурации компьютерной системы, работающей под Windows.

class Win32_BootConfiguration : CIM_Setting
{
  string BootDirectory;
  string Caption;
  string ConfigurationPath;
  string Description;
  string LastDrive;
  string Name;
  string ScratchDirectory;
  string SettingID;
  string TempDirectory;
};

Методы

Класс не имеет методов

Свойства

BootDirectory
Только для чтения. Путь к системным файлам, необходимым для загрузки системы. Например, C:\Windows
Caption
Только для чтения. Короткое описание (64 символа) объекта в одну строчку.
ConfigurationPath
Только для чтения. Путь к конфигурационным файлам. Это свойство может быть схожим со свойством BootDirectory.
Description
Только для чтения. Описание объекта CIM_Setting.
LastDrive
Только для чтения. Последняя буква диска, к которому сопоставлен физический диск. Например, E:
Name
Только для чтения. Имя загрузочной конфигурации, которое является его идентификатором.
ScratchDirectory
Только для чтения. Папка, в которой могут размещаться временные файлы во время загрузки системы.
SettingID
Только для чтения. Идентификатор, по которому определяется объект CIM_Setting.
TempDirectory
Только для чтения. Папка для временных файлов.

Примечания

Класс Win32_BootConfiguration наследует от CIM_Setting.

Пример

Пример с применением сценария VBS

Option Explicit

Dim objWMI
Dim colClass
Dim objClass

Dim strComputer

strComputer = "."
Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colClass = objWMI.ExecQuery("Select * from Win32_BootConfiguration",,48)

On Error Resume Next

For Each objClass in colClass
WScript.Echo "BootDirectory: " & objClass.BootDirectory
WScript.Echo "Caption: " & objClass.Caption
WScript.Echo "Name: " & objClass.Name
WScript.Echo "TempDirectory: " & objClass.TempDirectory
Next

Set objWMI = Nothing
Set colClass = Nothing
Set objClass = Nothing

[PowerShell]
# wmi-getbootconfiguration.ps1
# demonstrates the use of the Win32_BootConfiguration WMI class

# Get Boot configuration from WMI
$boot = Get-WMIObject Win32_BootConfiguration
# Display information
"Boot Directory     : {0}" -f $boot.bootdirectory
"Caption            : {0}" -f $boot.caption
"Description        : {0}" -f $boot.description
"Last Drive         : {0}" -f $boot.lastdrive
"Scratch Directory  : {0}" -f $boot.scratchdirectory
"Temp Directory     : {0}" -f $boot.tempdirectory

Смотри также

Operating System Classes


Win32_CodecFile

Класс Win32_CodecFile представляют информацию об установленных в системе аудио и видео- кодеках. Кодеки конвертируют один мультимедийный формат в другой, обычно из сжатого в формата в несжатый формат. Слово кодек происходит из комбинации двух слов - compress и decompress.

class Win32_CodecFile : CIM_DataFile
{
  uint32 AccessMask;
  boolean Archive;
  string Caption;
  boolean Compressed;
  string CompressionMethod;
  string CreationClassName;
  datetime CreationDate;
  string CSCreationClassName;
  string CSName;
  string Description;
  string Drive;
  string EightDotThreeFileName;
  boolean Encrypted;
  string EncryptionMethod;
  string Extension;
  string FileName;
  uint64 FileSize;
  string FileType;
  string FSCreationClassName;
  string FSName;
  string Group;
  boolean Hidden;
  datetime InstallDate;
  uint64 InUseCount;
  datetime LastAccessed;
  datetime LastModified;
  string Manufacturer;
  string Name;
  string Path;
  boolean Readable;
  string Status;
  boolean System;
  string Version;
  boolean Writeable;
};

Методы

Метод | Описание
ChangeSecurityPermissions | Changes the security permissions for the logical file specified in the object path.
ChangeSecurityPermissionsEx | Changes the security permissions for the logical file specified in the object path
Compress | Compresses the logical file (or directory) specified in the object path.
CompressEx | Compresses the logical file (or directory) specified in the object path.
Copy | Copies the logical file or directory specified in the object path to the location specified by the input parameter.
CopyEx | Class method that copies the logical file or directory specified in the object path to the location specified by the FileName parameter.
Delete | Deletes the logical file (or directory) specified in the object path.
DeleteEx | Deletes the logical file (or directory) specified in the object path.
GetEffectivePermission | Determines whether the caller has the aggregated permissions specified by the permission argument not only on the file object, but on the share the file or directory resides on (if it is on a share).
Rename | Class method that renames the logical file (or directory) specified in the object path.
TakeOwnerShip | Obtains ownership of the logical file specified in the object path.
TakeOwnerShipEx | Class method that obtains ownership of the logical file specified in the object path.
Uncompress | Uncompresses the logical file (or directory) specified in the object path.
UncompressEx | Uncompresses the logical file (or directory) specified in the object path.

Свойства

AccessMask Data type: uint32 Access type: Read-only Bitmask that represents the access rights required to access or perform specific operations on the codec file. For bit values, see File and Directory Access Rights Constants. Windows 2000 and Windows NT 4.0: On FAT volumes, the FULL_ACCESS value is returned instead, which indicates no security has been set on the object. Archive Data type: boolean Access type: Read-only If True, the file should be archived. This property is inherited from CIM_LogicalFile. Caption Data type: string Access type: Read-only Qualifiers: MaxLen(64) Short description (one-line string) of the object. This property is inherited from CIM_ManagedSystemElement. Compressed Data type: boolean Access type: Read-only If True, the file is compressed. This property is inherited from CIM_LogicalFile. CompressionMethod Data type: string Access type: Read-only Algorithm or tool used to compress the logical file. If it is not possible (or not desired) to describe the compression scheme (perhaps because it is not known), use the following words: "Unknown" to represent that it is not known whether the logical file is compressed or not; "Compressed" to represent that the file is compressed but either its compression scheme is not known or not disclosed; and "Not Compressed" to represent that the logical file is not compressed. This property is inherited from CIM_LogicalFile. CreationClassName Data type: string Access type: Read-only Qualifiers: MaxLen(256) Name of the first concrete class to appear in the inheritance chain used in the creation of an instance. When used with the other key properties of the class, the property allows all instances of this class and its subclasses to be uniquely identified. This property is inherited from CIM_LogicalFile. CreationDate Data type: datetime Access type: Read-only File creation date. This property is inherited from CIM_LogicalFile. CSCreationClassName Data type: string Access type: Read-only Class of the computer system. This property is inherited from CIM_LogicalFile. CSName Data type: string Access type: Read-only String representing the name of the computer system. This property is inherited from CIM_LogicalFile. Description Data type: string Access type: Read-only Full name of the codec driver. This string is intended to be displayed in large (descriptive) spaces. This property is inherited from CIM_ManagedSystemElement. Example: "Microsoft PCM Converter" Drive Data type: string Access type: Read-only Drive letter (including colon) of the file. This property is inherited from CIM_LogicalFile. Example: "c:" EightDotThreeFileName Data type: string Access type: Read-only DOS-compatible file name for this file. This property is inherited from CIM_LogicalFile. Example: "c:\progra~1" Encrypted Data type: boolean Access type: Read-only If True, the file is encrypted. This property is inherited from CIM_LogicalFile. EncryptionMethod Data type: string Access type: Read-only Algorithm or tool used to encrypt the logical file. If it is not possible (or not desired) to describe the encryption scheme (perhaps for security reasons), use the following words: "Unknown" to represent that it is not known whether the logical file is encrypted or not; "Encrypted" to represent that the file is encrypted but either its encryption scheme is not known or not disclosed; and "Not Encrypted" to represent that the logical file is not encrypted. This property is inherited from CIM_LogicalFile. Extension Data type: string Access type: Read-only File extension (without the dot). This property is inherited from CIM_LogicalFile. Examples: "txt", "mof", "mdb" FileName Data type: string Access type: Read-only Name (without the extension) of the file. This property is inherited from CIM_LogicalFile. Example: "autoexec" FileSize Data type: uint64 Access type: Read-only Size of the file (in bytes). This property is inherited from CIM_LogicalFile. For more information about using uint64 values in scripts, see Scripting in WMI. FileType Data type: string Access type: Read-only File type (indicated by the Extension property). This property is inherited from CIM_LogicalFile. FSCreationClassName Data type: string Access type: Read-only Class of the file system. This property is inherited from CIM_LogicalFile. FSName Data type: string Access type: Read-only Name of the file system. This property is inherited from CIM_LogicalFile. Group Data type: string Access type: Read-only Codec represented by this class. The values are: "Audio" "Video" Hidden Data type: boolean Access type: Read-only If True, the file is hidden. This property is inherited from CIM_LogicalFile. InstallDate Data type: datetime Access type: Read-only Object was installed. This property does not require a value to indicate that the object is installed. This property is inherited from CIM_ManagedSystemElement. InUseCount Data type: uint64 Access type: Read-only Number of "file opens" that are currently active against the file. This property is inherited from CIM_LogicalFile. For more information about using uint64 values in scripts, see Scripting in WMI. LastAccessed Data type: datetime Access type: Read-only File was last accessed. This property is inherited from CIM_LogicalFile. LastModified Data type: datetime Access type: Read-only File was last modified. This property is inherited from CIM_LogicalFile. Manufacturer Data type: string Access type: Read-only Manufacturer string from version resource, if one is present. This property is inherited from CIM_DataFile. Name Data type: string Access type: Read-only Qualifiers: Key Inherited name that serves as a key of a logical file instance within a file system. Full path names should be provided. This property is inherited from CIM_ManagedSystemElement. Example: "c:\winnt\system\win.ini" Path Data type: string Access type: Read-only Path of the file. This includes leading and trailing backslashes. This property is inherited from CIM_LogicalFile. Example: "\windows\system\" Readable Data type: boolean Access type: Read-only File can be read. This property is inherited from CIM_LogicalFile. Status Data type: string Access type: Read-only Qualifiers: MaxLen(10) Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, yet the managed element is neither "OK" nor in one of the other states. This property is inherited from CIM_ManagedSystemElement. The values are: "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service" System Data type: boolean Access type: Read-only If True, the file is a system file. This property is inherited from CIM_LogicalFile. Version Data type: string Access type: Read-only Version string from version resource, if one is present. This property is inherited from CIM_DataFile. Writeable Data type: boolean Access type: Read-only If True, the file can be written. This property is inherited from CIM_LogicalFile.

Примечания

Класс Win32_CodecFile наследует от CIM_DataFile.

Пример

Пример с применением сценария JS

var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;

var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_CodecFile", "WQL",
                                          wbemFlagReturnImmediately | wbemFlagForwardOnly);

var enumItems = new Enumerator(colItems);
var infoList;

for (; !enumItems.atEnd(); enumItems.moveNext())
{
    var objItem = enumItems.item();

    infoList = "Имя: " + objItem.Caption + "\r\n";
    infoList = infoList + "Расширение: " + objItem.Extension + "\r\n";
    infoList = infoList + "Тип кодека: " + objItem.Group + "\r\n";
    infoList = infoList + "Производитель: " + objItem.Manufacturer + "\r\n";
    infoList = infoList + "Версия: " + objItem.Version + "\r\n";
    WScript.Echo(infoList);
}

Пример с применением сценария VBS

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
   & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_CodecFile")

For Each objItem in colItems
   Wscript.Echo "Access Mask: " & objItem.AccessMask
   Wscript.Echo "Archive: " & objItem.Archive
   Wscript.Echo "Caption: " & objItem.Caption
   strCreationDate = WMIDateStringToDate(objItem.CreationDate)
   Wscript.Echo "Creation Date: " & strCreationdate
   Wscript.Echo "Drive: " & objItem.Drive
   Wscript.Echo "Eight Dot Three File Name: " & _
      objItem.EightDotThreeFileName
   Wscript.Echo "Extension: " & objItem.Extension
   Wscript.Echo "File Name: " & objItem.FileName
   Wscript.Echo "File Size: " & objItem.FileSize
   Wscript.Echo "File Type: " & objItem.FileType
   Wscript.Echo "File System Name: " & objItem.FSName
   Wscript.Echo "Group: " & objItem.Group
   Wscript.Echo "Hidden: " & objItem.Hidden
   strInstallDate = WMIDateStringToDate(objItem.InstallDate)
   Wscript.Echo "Last Accessed: " & strLastAccessed
   strLastModified = WMIDateStringToDate(objItem.LastModified)
   Wscript.Echo "Last Modified: " & strLastModified
   Wscript.Echo "Manufacturer: " & objItem.Manufacturer
   Wscript.Echo "Name: " & objItem.Name
   Wscript.Echo "Path: " & objItem.Path
   Wscript.Echo "Version: " & objItem.Version
Next

Function WMIDateStringToDate(dtmDate)
   WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
      Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
         & " " & Mid (dtmDate, 9, 2) & ":" & _
            Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate, _
               13, 2))
End Function

Пример на Visual Basic .NET

Imports System.Management

Module Module1
    Sub Main()
        Const QUERY As String = "SELECT * FROM Win32_CodecFile"
        Const PROPERTY_GROUP As String = "Group"
        Const PROPERTY_NAME As String = "Name"
        Const MESSAGE_TEMPLATE As String = "Имя:{0}; Тип кодека:{1}"

        Dim codecSearcher As ManagementObjectSearcher = New ManagementObjectSearcher(QUERY)
        Dim codecFile As ManagementObject
        For Each codecFile In codecSearcher.Get()
            Dim message As String = String.Format(MESSAGE_TEMPLATE, _
                        codecFile(PROPERTY_NAME), codecFile(PROPERTY_GROUP))
            Console.WriteLine(message)
        Next
        Console.ReadLine()
    End Sub
End Module

Смотри также

Operating System Classes


Win32_ComputerSystem

Класс Win32_ComputerSystem содержит информацию о компьютере, работающем в Windows.

class Win32_ComputerSystem : CIM_UnitaryComputerSystem
{
  uint16 AdminPasswordStatus;
  boolean AutomaticManagedPagefile;
  boolean AutomaticResetBootOption;
  boolean AutomaticResetCapability;
  uint16 BootOptionOnLimit;
  uint16 BootOptionOnWatchDog;
  boolean BootROMSupported;
  string BootupState;
  string Caption;
  uint16 ChassisBootupState;
  string CreationClassName;
  sint16 CurrentTimeZone;
  boolean DaylightInEffect;
  string Description;
  string DNSHostName;
  string Domain;
  uint16 DomainRole;
  boolean EnableDaylightSavingsTime;
  uint16 FrontPanelResetStatus;
  boolean InfraredSupported;
  string InitialLoadInfo;
  datetime InstallDate;
  uint16 KeyboardPasswordStatus;
  string LastLoadInfo;
  string Manufacturer;
  string Model;
  string Name;
  string NameFormat;
  boolean NetworkServerModeEnabled;
  uint32 NumberOfLogicalProcessors;
  uint32 NumberOfProcessors;
  uint8 OEMLogoBitmap[];
  string OEMStringArray[];
  boolean PartOfDomain;
  sint64 PauseAfterReset;
  uint16 PCSystemType;
  uint16 PowerManagementCapabilities[];
  boolean PowerManagementSupported;
  uint16 PowerOnPasswordStatus;
  uint16 PowerState;
  uint16 PowerSupplyState;
  string PrimaryOwnerContact;
  string PrimaryOwnerName;
  uint16 ResetCapability;
  sint16 ResetCount;
  sint16 ResetLimit;
  string Roles[];
  string Status;
  string SupportContactDescription[];
  uint16 SystemStartupDelay;
  string SystemStartupOptions[];
  uint8 SystemStartupSetting;
  string SystemType;
  uint16 ThermalState;
  uint64 TotalPhysicalMemory;
  string UserName;
  uint16 WakeUpType;
  string Workgroup;
};

Методы

Метод | Описание
JoinDomainOrWorkgroup | Добавляет компьютер в домен или рабочую группу
Rename | Переименовывает локальную машину
UnjoinDomainOrWorkgroup | Удаляет компьютер из домена или рабочей группы

Свойства

AdminPasswordStatus
Только для чтения. System hardware security settings for administrator password status. Value Meaning 1 0x1 Disabled 2 0x2 Enabled 3 0x3 Not Implemented 4 0x4 Unknown AutomaticManagedPagefile Data type: boolean Access type: Read/write If True, the system manages the page file. Windows Server 2003, Windows XP, and Windows 2000: This property is not available.
AutomaticResetBootOption
Read/write If True, the automatic reset boot option is enabled.
AutomaticResetCapability
Только для чтения. If True, the automatic reset is enabled. BootOptionOnLimit Data type: uint16 Access type: Только для чтения. Boot option limit is ON. Identifies the system action when the ResetLimit value is reached. Value Meaning 1 0x1 Reserved 2 0x2 Operating System 3 0x3 System Utilities 4 0x4 Do Not Reboot BootOptionOnWatchDog Data type: uint16 Access type: Только для чтения. Type of reboot action after the time on the watchdog timer is elapsed. Value Meaning 1 0x1 Reserved 2 0x2 Operating System 3 0x3 System Utilities 4 0x4 Do Not Reboot BootROMSupported Data type: boolean Access type: Только для чтения. If True, indicates whether a boot ROM is supported. BootupState Data type: string Access type: Только для чтения. System is started. Fail-safe boot bypasses the user startup files—also called SafeBoot. The following list contains the required values: "Normal boot" "Fail-safe boot" "Fail-safe with network boot" Caption Data type: string Access type: Только для чтения. Short description of the object—a one-line string. This property is inherited from CIM_ManagedSystemElement. ChassisBootupState Data type: uint16 Access type: Только для чтения. Boot up state of the chassis. Value Meaning 1 0x1 Other 2 0x2 Unknown 3 0x3 Safes 4 0x4 Warning 5 0x5 Critical 6 0x6 Nonrecoverable CreationClassName Data type: string Access type: Только для чтения. Name of the first concrete class in the inheritance chain of an instance. You can use this property with other properties of the class to identify all instances of the class and its subclasses. This property is inherited from CIM_System. CurrentTimeZone Data type: sint16 Access type: Read/write Qualifiers: Units(Minutes) Amount of time the unitary computer system is offset from Coordinated Universal Time (UTC). DaylightInEffect Data type: boolean Access type: Только для чтения. If True, the daylight savings mode is ON. Description Data type: string Access type: Только для чтения. Description of the object. DNSHostName Data type: string Access type: Только для чтения. Name of local computer according to the domain name server (DNS). Windows XP and Windows 2000: This property is not available. Domain Data type: string Access type: Только для чтения. Name of the domain to which a computer belongs. Note If the computer is not part of a domain, then the name of the workgroup is returned. DomainRole Data type: uint16 Access type: Только для чтения. Role of a computer in an assigned domain workgroup. A domain workgroup is a collection of computers on the same network. For example, a DomainRole property may show that a computer is a member workstation. This property is inherited from CIM_ManagedSystemElement. Value Meaning 0 0x0 Standalone Workstation 1 0x1 Member Workstation 2 0x2 Standalone Server 3 0x3 Member Server 4 0x4 Backup Domain Controller 5 0x5 Primary Domain Controller EnableDaylightSavingsTime Data type: boolean Access type: Read/write Enables daylight savings time (DST) on a computer. A value of True indicates that the system time changes to an hour ahead or behind when DST starts or ends. A value of False indicates that the system time does not change to an hour ahead or behind when DST starts or ends. A value of NULL indicates that the DST status is unknown on a system. FrontPanelResetStatus Data type: uint16 Access type: Только для чтения. The following table lists the hardware security settings for the reset button on a computer. Value Meaning 0 0x0 Disabled 1 0x1 Enabled 2 0x2 Not Implemented 3 0x3 Unknown InfraredSupported Data type: boolean Access type: Только для чтения. If True, an infrared (IR) port exists on a computer system. InitialLoadInfo Data type: string Access type: Только для чтения. Data required to find the initial load device or boot service to request that the operating system start up. This property is inherited from CIM_UnitaryComputerSystem. InstallDate Data type: datetime Access type: Только для чтения. Object is installed. An object does not need a value to indicate that it is installed. This property is inherited from CIM_ManagedSystemElement. KeyboardPasswordStatus Data type: uint16 Access type: Только для чтения. System hardware security settings for Keyboard Password Status. Value Meaning 0 0x0 Disabled 1 0x1 Enabled 2 0x2 Not Implemented 3 0x3 Unknown LastLoadInfo Data type: string Access type: Только для чтения. Array entry of the InitialLoadInfo property that contains the data to start the loaded operating system. This property is inherited from CIM_UnitaryComputerSystem. Manufacturer Data type: string Access type: Только для чтения. Name of a computer manufacturer. Example: Adventure Works Model Data type: string Access type: Только для чтения. Product name that a manufacturer gives to a computer. This property must have a value. Name Data type: string Access type: Только для чтения. Key of a CIM_System instance in an enterprise environment. This property is inherited from CIM_ManagedSystemElement. NameFormat Data type: string Access type: Только для чтения. Computer system Name value that is generated automatically. The CIM_ComputerSystem object and its derivatives are top-level objects of the Common Information Model (CIM). They provide the scope for several components. Unique CIM_System keys are required, but you can define a heuristic to create the CIM_ComputerSystem name that generates the same name, and is independent from the discovery protocol. This prevents inventory and management problems when the same asset or entity is discovered multiple times, but cannot be resolved to one object. Using a heuristic is recommended, but not required. The heuristic is outlined in the CIM V2 Common Model specification, and assumes that the documented rules are used to determine and assign a name. The NameFormat values list defines the order to assign a computer system name. Several rules map to the same value. The CIM_ComputerSystem Name value that is calculated using the heuristic is the key value of the system. However, use aliases to assign a different name for CIM_ComputerSystem, which can be more unique to your company. This property is inherited from CIM_System. The following list identifies the values for this property. "IP" "Dial" "HID" "NWA" "HWA" "X25" "ISDN" "IPX" "DCC" "ICD" "E.164" "SNA" "OID/OSI" "Other" NetworkServerModeEnabled Data type: boolean Access type: Только для чтения. If True, the network Server Mode is enabled. NumberOfLogicalProcessors Data type: uint32 Access type: Только для чтения. Number of logical processors available on the computer. You can use NumberOfLogicalProcessors and NumberOfProcessors to determine if the computer is hyperthreading. For more information, see Remarks. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. NumberOfProcessors Data type: uint32 Access type: Только для чтения. Number of physical processors currently available on a system. This is the number of enabled processors for a system, which does not include the disabled processors. If a computer system has two physical processors each containing two logical processors, then the value of NumberOfProcessors is 2 and NumberOfLogicalProcessors is 4. The processors may be multicore or they may be hyperthreading processors. For more information, see Remarks. Windows Server 2003, Windows XP, and Windows 2000: Because the NumberOfLogicalProcessors property is not available, NumberOfProcessors indicates the number of logical processors available in the system. In the case of a computer system that has two physical processors each containing two logical processors, the value of NumberOfProcessors is 4. OEMLogoBitmap Data type: uint8 array Access type: Только для чтения. List of data for a bitmap that the original equipment manufacturer (OEM) creates. OEMStringArray Data type: string array Access type: Только для чтения. List of free-form strings that an OEM defines. For example, an OEM defines the part numbers for system reference documents, manufacturer contact information, and so on. PartOfDomain Data type: boolean Access type: Только для чтения. If True, the computer is part of a domain. If the value is NULL, the computer is not in a domain or the status is unknown. If you unjoin the computer from a domain, the value becomes false. Windows 2000 and Windows NT: This property is not available. PauseAfterReset Data type: sint64 Access type: Только для чтения. Qualifiers: Units(Milliseconds) Time delay before a reboot is initiated—in milliseconds. It is used after a system power cycle, local or remote system reset, and automatic system reset. A value of –1 (minus one) indicates that the pause value is unknown. PCSystemType Data type: uint16 Access type: Только для чтения. Type of the computer in use, such as laptop, desktop, or Tablet. Windows Server 2003, Windows XP, Windows 2000, Windows NT 4.0, and Windows Me/98/95: This property is not available. Value Meaning 0 0x0 Unspecified 1 0x1 Desktop 2 0x2 Mobile 3 0x3 Workstation 4 0x4 Enterprise Server 5 0x5 Small Office and Home Office (SOHO) Server 6 0x6 Appliance PC 7 0x7 Performance Server 8 0x8 Maximum PowerManagementCapabilities Data type: uint16 array Access type: Только для чтения. Array of the specific power-related capabilities of a logical device. This property is inherited from CIM_LogicalDevice. Value Meaning 0 0x0 Unknown 1 0x1 Not Supported 2 0x2 Disabled 3 0x3 Enabled The power management features are currently enabled, but the exact feature set is unknown or the information is unavailable. 4 0x4 Power Saving Modes Entered Automatically The device can change its power state based on usage or other criteria. 5 0x5 Power State Settable The SetPowerState method is supported. This method is found on the parent CIM_LogicalDevice class and can be implemented. For more information, see Designing Managed Object Format (MOF) Classes. 6 0x6 Power Cycling Supported The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle). 7 0x7 Timed Power-On Supported The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle) and Time set to a specific date and time, or interval, for power-on. PowerManagementSupported Data type: boolean Access type: Только для чтения. If True, device can be power-managed, for example, a device can be put into suspend mode, and so on. This property does not indicate that power management features are enabled currently, but it does indicate that the logical device is capable of power management. This property is inherited from CIM_UnitaryComputerSystem. PowerOnPasswordStatus Data type: uint16 Access type: Только для чтения. System hardware security settings for Power-On Password Status. Value Meaning 0 0x0 Disabled 1 0x1 Enabled 2 0x2 Not Implemented 3 0x3 Unknown PowerState Data type: uint16 Access type: Только для чтения. Current power state of a computer and its associated operating system. The power saving states have the following values: Value 4 (Unknown) indicates that the system is known to be in a power save mode, but its exact status in this mode is unknown; 2 (Low Power Mode) indicates that the system is in a power save state, but still functioning and may exhibit degraded performance; 3 (Standby) indicates that the system is not functioning, but could be brought to full power quickly; and 7 (Warning) indicates that the computer system is in a warning state and a power save mode. This property is inherited from CIM_UnitaryComputerSystem. Value Meaning 0 0x0 Unknown 1 0x1 Full Power 2 0x2 Power Save - Low Power Mode 3 0x3 Power Save - Standby 4 0x4 Power Save - Unknown 5 0x5 Power Cycle 6 0x6 Power Off 7 0x7 Power Save - Warning PowerSupplyState Data type: uint16 Access type: Только для чтения. State of the power supply or supplies when last booted. The following list identifies the values for this property. Value Meaning 1 0x1 Other 2 0x2 Unknown 3 0x3 Safe 4 0x4 Warning 5 0x5 Critical 6 0x6 Nonrecoverable PrimaryOwnerContact Data type: string Access type: Только для чтения. Contact information for the primary system owner, for example, phone number, e-mail address, and so on. This property is inherited from CIM_System. PrimaryOwnerName Data type: string Access type: Только для чтения. Name of the primary system owner. This property is inherited from CIM_System. ResetCapability Data type: uint16 Access type: Только для чтения. If enabled, the value is 4 and the unitary computer system can be reset using the power and reset buttons. If disabled, the value is 3, and a reset is not allowed. This property is inherited from CIM_UnitaryComputerSystem. Value Meaning 1 0x1 Other 2 0x2 Unknown 3 0x3 Disabled 4 0x4 Enabled 5 0x5 Nonrecoverable ResetCount Data type: sint16 Access type: Только для чтения. Number of automatic resets since the last reset. A value of –1 (minus one) indicates that the count is unknown. ResetLimit Data type: sint16 Access type: Только для чтения. Number of consecutive times a system reset is attempted. A value of –1 (minus one) indicates that the limit is unknown. Roles Data type: string array Access type: Read/write List that specifies the roles of a system in the information technology environment. This property is inherited from CIM_System. Status Data type: string Access type: Только для чтения. Qualifiers: MaxLen(10) Current status of an object. Various operational and nonoperational statuses can be defined. Operational statuses include: OK, Degraded, and Pred Fail, which is an element such as a SMART-enabled hard disk drive that may be functioning properly, but predicts a failure in the near future. Nonoperational statuses include: Error, Starting, Stopping, and Service, which can apply during mirror-resilvering of a disk, reloading a user permissions list, or other administrative work. Not all status work is online, but the managed element is not OK or in one of the other states. This property is inherited from CIM_ManagedSystemElement. The following list identifies the values for this property. "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service" SupportContactDescription Data type: string array Access type: Только для чтения. List of the support contact information for the Windows operating system. SystemStartupDelay Data type: uint16 Access type: Read/write Qualifiers: Units(Seconds) Time to delay before starting the Windows operating system—in seconds. Beginning with Windows Vista, SystemStartupDelay is obsolete because Boot.ini is not used to configure system startup. Instead, use the BCD classes supplied by the Boot Configuration Data (BCD) WMI provider or the Bcdedit command. Windows Server 2003, Windows XP, and Windows 2000: This property is available and supported. You can use SystemStartupDelay, with SystemStartupSetting and SystemStartupOptions to modify Boot.ini system startup settings. SystemStartupOptions Data type: string array Access type: Только для чтения. List of the options for starting up the coumputer system running Windows. This property must have a value. Beginning with Windows Vista, SystemStartupOptions is obsolete because Boot.ini is not used to configure system startup. Instead, use the BCD classes supplied by the Boot Configuration Data (BCD) WMI provider or the Bcdedit command. Windows Server 2003, Windows XP, and Windows 2000: This property is available and supported. You can use SystemStartupOptions, with SystemStartupSetting and SystemStartupDelay to modify Boot.ini system startup settings. SystemStartupSetting Data type: uint8 Access type: Read/write Index of the default startup profile. This value is calculated so that it usually returns 0 (zero), because at write-time the profile string is physically moved to the top of the list, which is how Windows NT determines the default value. Beginning with Windows Vista, SystemStartupSetting is obsolete because Boot.ini is not used to configure system startup. Instead, use the BCD classes supplied by the Boot Configuration Data (BCD) WMI provider or the Bcdedit command. Windows Server 2003, Windows XP, and Windows 2000: This property is available and supported. You can use SystemStartupSetting, with SystemStartupDelay and SystemStartupOptions to modify Boot.ini system startup settings. SystemType Data type: string Access type: Только для чтения. System running on the Windows-based computer. This property must have a value. The following list identifies the values for this property. "X86-based PC" "MIPS-based PC" "Alpha-based PC" "Power PC" "SH-x PC" "StrongARM PC" "64-bit Intel PC" "64-bit Alpha PC" "Unknown" "X86-Nec98 PC" ThermalState Data type: uint16 Access type: Только для чтения. Thermal state of the system when last booted. Value Meaning 1 0x1 Other 2 0x2 Unknown 3 0x3 Safe 4 0x4 Warning 5 0x5 Critical 6 0x6 Nonrecoverable TotalPhysicalMemory Data type: uint64 Access type: Только для чтения. Qualifiers: Units(Bytes) Total size of physical memory. Be aware that, under some circumstances, this property may not return an accurate value for the physical memory. For example, it is not accurate if the BIOS is using some of the physical memory. For an accurate value, use the Capacity property in Win32_PhysicalMemory instead. Example: 67108864 For more information about using uint64 values in scripts, see Scripting in WMI. UserName Data type: string Access type: Только для чтения. Name of a user that is logged on currently. This property must have a value. In a terminal services session, UserName returns the name of the user that is logged on to the console—not the user logged on during the terminal service session. Example: jeffsmith WakeUpType Data type: uint16 Access type: Только для чтения. Event that causes the system to power up. Value Meaning 0 0x0 Reserved 1 0x1 Other 2 0x2 Unknown 3 0x3 APM Timer 4 0x4 Modem Ring 5 0x5 LAN Remote 6 0x6 Power Switch 7 0x7 PCI PME# 8 0x8 AC Power Restored Workgroup Data type: string Access type: Read/write Name of the workgroup for this computer. If the value of the PartOfDomain property is False, then the name of the workgroup is returned. Windows 2000 and Windows NT: This property is not available.

Примечания

Remarks To determine the total number of processor instances associated with a computer system object, use the Win32_ComputerSystemProcessor association class. A Win32_ComputerSystem instance that has multiple physical processors has multiple Win32_Processor instances associated with it. If the value of NumberOfLogicalProcessors is greater than the value of NumberOfProcessors then the computer system is either a multicore system or has one or more processors enabled for hyperthreading. For more information, see the NumberOfLogicalProcessors and NumberOfCores properties and Remarks section in Win32_Processor. Windows Server 2003 and Windows XP: A single-processor computer system with hyperthreading architecture has more than one Win32_Processor instance associated with it. You cannot distinguish a computer that is hyperthreading from a computer with multiple physical processors. For example, the value of NumberOfProcessors is 2 for both a hyperthreading computer and a computer with two physical processors. Windows 2000, Windows NT 4.0, and Windows Me/98/95: Hyperthreading is not supported by the operating system. A computer system only has one processor associated with it.

Класс Win32_ComputerSystem наследует от CIM_UnitaryComputerSystem.

Пример

Пример с применением сценария VBS

' Определяем тип компьютера
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem")

Select Case colItems.ItemIndex(0).PCSystemType
    Case 0
        Wscript.Echo "Unspecified"
    Case 1
        Wscript.Echo "Desktop"
    Case 2
        Wscript.Echo "Mobile"
    Case 3
        Wscript.Echo "Workstation"
    Case 4
        Wscript.Echo "Enterprise Server"
    Case 5
        Wscript.Echo "SOHO Server"
    Case 6
        Wscript.Echo "Applicance PC"
    Case 7
        Wscript.Echo "Performance Server"
    Case 8
        Wscript.Echo "Role Maximum"
End Select

Пример для Visual Basic 2008 можно скачать со страницы примеров.

Смотри также

Operating System Classes


Win32_LogicalProgramGroup

Класс Win32_LogicalProgramGroup содержит список групп программ на компьютере под управлением Windows, например Автозагрузка или Стандартные.

class Win32_LogicalProgramGroup : Win32_ProgramGroupOrItem
{
  string Caption;
  string Description;
  string GroupName;
  datetime InstallDate;
  string Name;
  string Status;
  string UserName;
};

Методы

Класс Win32_LogicalProgramGroup не содержит методов.

Свойства

Caption
Короткое описание объекта (в одну строчку). Только для чтения.
Description
Описание объекта. Только для чтения
GroupName
Имя программной группы. Программные группы представлены в виде папок (например, Стандартные\Служебные). Только для чтения
InstallDate
Дата установки объекта. Только для чтения
Name
Имя, определенное пользователем, за которым следует имя группы. Например, All Users:Accessories\System Tools. Только для чтения
Status
Текущее состояние объекта. Возможны значения OK, Degraded, Pred Fail, Error, Starting, Stopping, Service. Только для чтения
UserName
Пользователи, которые имеют доступ к программной группе. Например, All Users. Только для чтения.

Примечания

Класс Win32_LogicalProgramGroup наследует от Win32_ProgramGroupOrItem. Вызывающий процесс, который вызывает этот класс, должен иметь привилегию SE_RESTORE_NAME на машине.

Пример

Пример с применением сценария VBS

strComputer = "."
Set objWMILogProgGroup = GetObject("winmgmts:\\" & strComputer &

"\root\cimv2").ExecQuery ("Select * from Win32_LogicalProgramGroup")

For each progGroup in objWMILogProgGroup
    Wscript.Echo progGroup.Caption
Next


Win32_NetworkAdapter

Класс Win32_NetworkAdapter содержит информацию о сетевом адаптере на компьютере под управлением Windows. Класс поддерживает только IPv4.

class Win32_NetworkAdapter : CIM_NetworkAdapter
{
  string AdapterType;
  uint16 AdapterTypeID;
  boolean AutoSense;
  uint16 Availability;
  string Caption;
  uint32 ConfigManagerErrorCode;
  boolean ConfigManagerUserConfig;
  string CreationClassName;
  string Description;
  string DeviceID;
  boolean ErrorCleared;
  string ErrorDescription;
  string GUID;
  uint32 Index;
  datetime InstallDate;
  boolean Installed;
  uint32 InterfaceIndex;
  uint32 LastErrorCode;
  string MACAddress;
  string Manufacturer;
  uint32 MaxNumberControlled;
  uint64 MaxSpeed;
  string Name;
  string NetConnectionID;
  uint16 NetConnectionStatus;
  boolean NetEnabled;
  string NetworkAddresses[];
  string PermanentAddress;
  boolean PhysicalAdapter;
  string PNPDeviceID;
  uint16 PowerManagementCapabilities[];
  boolean PowerManagementSupported;
  string ProductName;
  string ServiceName;
  uint64 Speed;
  string Status;
  uint16 StatusInfo;
  string SystemCreationClassName;
  string SystemName;
  datetime TimeOfLastReset;
};

Методы

Метод | Описание
Enable | Включает сетевой адаптер (Windows Vista)
Disable | Выключает сетевой адаптер (Windows Vista)

Свойства

AdapterType Data type: string Access type: Read-only Network medium in use. Windows NT: This property may not be applicable to all types of network adapters listed within this class. The network adpaters are: "Ethernet 802.3" "Token Ring 802.5" "Fiber Distributed Data Interface (FDDI)" "Wide Area Network (WAN)" "LocalTalk" "Ethernet using DIX header format" "ARCNET" "ARCNET (878.2)" "ATM" "Wireless" "Infrared Wireless" "Bpc" "CoWan" "1394" AdapterTypeID Data type: uint16 Access type: Read-only Network medium in use. Returns the same information as the AdapterType property, except that the information is in the form of an integer. Windows 2000 and Windows NT 4.0: This property is not applicable. Value Meaning 0 0x0 Ethernet 802.3 1 0x1 Token Ring 802.5 2 0x2 Fiber Distributed Data Interface (FDDI) 3 0x3 Wide Area Network (WAN) 4 0x4 LocalTalk 5 0x5 Ethernet using DIX header format 6 0x6 ARCNET 7 0x7 ARCNET (878.2) 8 0x8 ATM 9 0x9 Wireless 10 0xA Infrared Wireless 11 0xB Bpc 12 0xC CoWan 13 0xD 1394 AutoSense Data type: boolean Access type: Read-only If True, the network adapter can automatically determine the speed of the attached or network media. This property is inherited from CIM_NetworkAdapter. This property has not been implemented yet. It returns a NULL value by default. Availability Data type: uint16 Access type: Read-only Availability and status of the device. Inherited from CIM_LogicalDevice. Value Meaning 1 0x1 Other 2 0x2 Unknown 3 0x3 Running or Full Power 4 0x4 Warning 5 0x5 In Test 6 0x6 Not Applicable 7 0x7 Power Off 8 0x8 Off Line 9 0x9 Off Duty 10 0xA Degraded 11 0xB Not Installed 12 0xC Install Error 13 0xD Power Save - Unknown The device is known to be in a power save state, but its exact status is unknown. 14 0xE Power Save - Low Power Mode The device is in a power save state, but still functioning, and may exhibit degraded performance. 15 0xF Power Save - Standby The device is not functioning, but could be brought to full power quickly. 16 0x10 Power Cycle 17 0x11 Power Save - Warning The device is in a warning state, though also in a power save state. Caption Data type: string Access type: Read-only Short description of the object—a one-line string. This property is inherited from CIM_ManagedSystemElement. ConfigManagerErrorCode Data type: uint32 Access type: Read-only Windows Configuration Manager error code. Value Meaning 0 0x0 Device is working properly. 1 0x1 Device is not configured correctly. 2 0x2 Windows cannot load the driver for this device. 3 0x3 Driver for this device might be corrupted, or the system may be low on memory or other resources. 4 0x4 Device is not working properly. One of its drivers or the registry might be corrupted. 5 0x5 Driver for the device requires a resource that Windows cannot manage. 6 0x6 Boot configuration for the device conflicts with other devices. 7 0x7 Cannot filter. 8 0x8 Driver loader for the device is missing. 9 0x9 Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device. 10 0xA Device cannot start. 11 0xB Device failed. 12 0xC Device cannot find enough free resources to use. 13 0xD Windows cannot verify the device's resources. 14 0xE Device cannot work properly until the computer is restarted. 15 0xF Device is not working properly due to a possible re-enumeration problem. 16 0x10 Windows cannot identify all of the resources that the device uses. 17 0x11 Device is requesting an unknown resource type. 18 0x12 Device drivers must be reinstalled. 19 0x13 Failure using the VxD loader. 20 0x14 Registry might be corrupted. 21 0x15 System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device. 22 0x16 Device is disabled. 23 0x17 System failure. If changing the device driver is ineffective, see the hardware documentation. 24 0x18 Device is not present, not working properly, or does not have all of its drivers installed. 25 0x19 Windows is still setting up the device. 26 0x1A Windows is still setting up the device. 27 0x1B Device does not have valid log configuration. 28 0x1C Device drivers are not installed. 29 0x1D Device is disabled. The device firmware did not provide the required resources. 30 0x1E Device is using an IRQ resource that another device is using. 31 0x1F Device is not working properly. Windows cannot load the required device drivers. ConfigManagerUserConfig Data type: boolean Access type: Read-only If True, the device is using a user-defined configuration. This property is inherited from CIM_LogicalDevice. CreationClassName Data type: string Access type: Read-only Qualifiers: Key, MaxLen(256) Name of the first concrete class to appear in the inheritance chain used in the creation of an instance. When used with the other key properties of the class, the property allows all instances of this class and its subclasses to be uniquely identified. This property is inherited from CIM_LogicalDevice. Description Data type: string Access type: Read-only Description of the object. This property is inherited from CIM_ManagedSystemElement. DeviceID Data type: string Access type: Read-only Qualifiers: Key Unique identifier of the network adapter from other devices on the system. This property is inherited from CIM_LogicalDevice. ErrorCleared Data type: boolean Access type: Read-only If True, the error reported in LastErrorCode is now cleared. This property is inherited from CIM_LogicalDevice. ErrorDescription Data type: string Access type: Read-only More information about the error recorded in LastErrorCode, and information about any corrective actions that may be taken. This property is inherited from CIM_LogicalDevice. GUID Data type: string Access type: Read-only Globally unique identifier for the connection. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property is not available. Index Data type: uint32 Access type: Read-only Index number of the network adapter, stored in the system registry. Example: 0 InstallDate Data type: datetime Access type: Read-only Date and time the object was installed. This property does not need a value to indicate that the object is installed. This property is inherited from CIM_ManagedSystemElement. This property has not been implemented yet. It returns a NULL value by default. Installed Data type: boolean Access type: Read-only Qualifiers: Deprecated If True, the network adapter is installed in the system. InterfaceIndex Data type: uint32 Access type: Read-only Index value that uniquely identifies the local network interface. The value in this property is the same as the value in the InterfaceIndex property in the instance of Win32_IP4RouteTable that represents the network interface in the route table. Windows XP, Windows 2000, and Windows NT 4.0: This property is not available. LastErrorCode Data type: uint32 Access type: Read-only Last error code reported by the logical device. This property is inherited from CIM_LogicalDevice. MACAddress Data type: string Access type: Read-only Media access control address for this network adapter. A MAC address is a unique 48-bit number assigned to the network adapter by the manufacturer. It uniquely identifies this network adapter and is used for mapping TCP/IP network communications. Manufacturer Data type: string Access type: Read-only Name of the network adapter's manufacturer. Example: "3COM" MaxNumberControlled Data type: uint32 Access type: Read-only Maximum number of directly addressable ports supported by this network adapter. A value of 0 (zero) should be used if the number is unknown. MaxSpeed Data type: uint64 Access type: Read-only Maximum speed, in bits per second, for the network adapter. This property is inherited from CIM_NetworkAdapter. This property has not been implemented yet. It returns a NULL value by default. For more information about using uint64 values in scripts, see Scripting in WMI. Name Data type: string Access type: Read-only Label by which the object is known. When subclassed, the property can be overridden to be a key property. This property is inherited from CIM_ManagedSystemElement. NetConnectionID Data type: string Access type: Read/write Name of the network connection as it appears in the Network Connections Control Panel program. Windows Server 2003 and Windows XP: This property is read-only. Windows 2000 and Windows NT 4.0: This property is not available. NetConnectionStatus Data type: uint16 Access type: Read-only State of the network adapter connection to the network. Windows 2000 and Windows NT 4.0: This property is not available. Value Meaning 0 0x0 Disconnected 1 0x1 Connecting 2 0x2 Connected 3 0x3 Disconnecting 4 0x4 Hardware not present 5 0x5 Hardware disabled 6 0x6 Hardware malfunction 7 0x7 Media disconnected 8 0x8 Authenticating 9 0x9 Authentication succeeded 10 0xA Authentication failed 11 0xB Invalid address 12 0xC Credentials required NetEnabled Data type: boolean Access type: Read-only Indicates whether the adapter is enabled or not. If True, the adapter is enabled. You can enable or disable the NIC by using the Enable and Disable methods. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property is not available. NetworkAddresses Data type: string array Access type: Read-only Array of network addresses for an adapter. This property is inherited from CIM_NetworkAdapter. This property has not been implemented yet. It returns a NULL value by default. PermanentAddress Data type: string Access type: Read-only Network address hard-coded into an adapter. This hard-coded address may be changed by firmware upgrade or software configuration. If so, this field should be updated when the change is made. The property should be left blank if no hard-coded address exists for the network adapter. This property is inherited from CIM_NetworkAdapter. This property has not been implemented yet. It returns a NULL value by default. PhysicalAdapter Data type: boolean Access type: Read-only Indicates whether the adapter is a physical or a logical adapter. If True, the adapter is physical. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property is not available. PNPDeviceID Data type: string Access type: Read-only Windows Plug and Play device identifier of the logical device. This property is inherited from CIM_LogicalDevice. Example: "*PNP030b" PowerManagementCapabilities Data type: uint16 array Access type: Read-only Array of the specific power-related capabilities of a logical device. This property is inherited from CIM_LogicalDevice. Value Meaning 0 0x0 Unknown 1 0x1 Not Supported 2 0x2 Disabled 3 0x3 Enabled The power management features are currently enabled but the exact feature set is unknown or the information is unavailable. 4 0x4 Power Saving Modes Entered Automatically The device can change its power state based on usage or other criteria. 5 0x5 Power State Settable The SetPowerState method is supported. This method is found on the parent CIM_LogicalDevice class and can be implemented. For more information, see Designing Managed Object Format (MOF) Classes. 6 0x6 Power Cycling Supported The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle). 7 0x7 Timed Power-On Supported The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle) and Time set to a specific date and time, or interval, for power-on. PowerManagementSupported Data type: boolean Access type: Read-only If True, the device can be power-managed (can be put into suspend mode, and so on). The property does not indicate that power management features are currently enabled, only that the logical device is capable of power management. This property is inherited from CIM_LogicalDevice. ProductName Data type: string Access type: Read-only Product name of the network adapter. Example: "Fast EtherLink XL" ServiceName Data type: string Access type: Read-only Service name of the network adapter. This name is usually shorter than the full product name. Example: "Elnkii" Speed Data type: uint64 Access type: Read-only Estimate of the current bandwidth in bits per second. For endpoints which vary in bandwidth or for those where no accurate estimation can be made, this property should contain the nominal bandwidth. This property is inherited from CIM_NetworkAdapter. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property has not been implemented yet. It returns a NULL value by default. For more information about using uint64 values in scripts, see Scripting in WMI. Status Data type: string Access type: Read-only Current status of the object. This property is inherited from CIM_ManagedSystemElement. The values are: "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service" StatusInfo Data type: uint16 Access type: Read-only State of the logical device. If this property does not apply to the logical device, the value 5 (Not Applicable) should be used. This property is inherited from CIM_LogicalDevice. Value Meaning 1 0x1 Other 2 0x2 Unknown 3 0x3 Enabled 4 0x4 Disabled 5 0x5 Not Applicable SystemCreationClassName Data type: string Access type: Read-only Value of the scoping computer's CreationClassName property. This property is inherited from CIM_LogicalDevice. SystemName Data type: string Access type: Read-only Name of the scoping system. This property is inherited from CIM_LogicalDevice. TimeOfLastReset Data type: datetime Access type: Read-only Date and time the network adapter was last reset.

Примечания

Класс Win32_NetworkAdapter наследует от CIM_NetworkAdapter.

Пример

Пример с применением сценария VBS

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter")

For Each objItem in colItems
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo
Next

*** Включение сетевых адаптеров ***
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapter Where NetEnabled = 'False'")

For Each objItem in colItems
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Description: " & objItem.Description
    objItem.Enable
    Wscript.Echo
Next

Смотри также

Computer System Hardware Classes


Win32_NetworkAdapterConfiguration

Класс Win32_NetworkAdapterConfiguration содержит атрибуты и поведение сетевого адаптера. Класс включает дополнительные свойства и методы, которые поддерживают управление протоколами TCP/IP и Internetwork Packet Exchange (IPX)

class Win32_NetworkAdapterConfiguration : CIM_Setting
{
  boolean ArpAlwaysSourceRoute;
  boolean ArpUseEtherSNAP;
  string Caption;
  string DatabasePath;
  boolean DeadGWDetectEnabled;
  string DefaultIPGateway[];
  uint8 DefaultTOS;
  uint8 DefaultTTL;
  string Description;
  boolean DHCPEnabled;
  datetime DHCPLeaseExpires;
  datetime DHCPLeaseObtained;
  string DHCPServer;
  string DNSDomain;
  string DNSDomainSuffixSearchOrder[];
  boolean DNSEnabledForWINSResolution;
  string DNSHostName;
  string DNSServerSearchOrder[];
  boolean DomainDNSRegistrationEnabled;
  uint32 ForwardBufferMemory;
  boolean FullDNSRegistrationEnabled;
  uint16 GatewayCostMetric[];
  uint8 IGMPLevel;
  uint32 Index;
  uint32 InterfaceIndex;
  string IPAddress[];
  uint32 IPConnectionMetric;
  boolean IPEnabled;
  boolean IPFilterSecurityEnabled;
  boolean IPPortSecurityEnabled;
  string IPSecPermitIPProtocols[];
  string IPSecPermitTCPPorts[];
  string IPSecPermitUDPPorts[];
  string IPSubnet[];
  boolean IPUseZeroBroadcast;
  string IPXAddress;
  boolean IPXEnabled;
  uint32 IPXFrameType[];
  uint32 IPXMediaType;
  string IPXNetworkNumber[];
  string IPXVirtualNetNumber;
  uint32 KeepAliveInterval;
  uint32 KeepAliveTime;
  string MACAddress;
  uint32 MTU;
  uint32 NumForwardPackets;
  boolean PMTUBHDetectEnabled;
  boolean PMTUDiscoveryEnabled;
  string ServiceName;
  string SettingID;
  uint32 TcpipNetbiosOptions;
  uint32 TcpMaxConnectRetransmissions;
  uint32 TcpMaxDataRetransmissions;
  uint32 TcpNumConnections;
  boolean TcpUseRFC1122UrgentPointer;
  uint16 TcpWindowSize;
  boolean WINSEnableLMHostsLookup;
  string WINSHostLookupFile;
  string WINSPrimaryServer;
  string WINSScopeID;
  string WINSSecondaryServer;
};

Методы

Метод | Описание
DisableIPSec | Disables IP security on this TCP/IP-enabled network adapter.
EnableDHCP | Enables the Dynamic Host Configuration Protocol (DHCP) for service with this network adapter.
EnableDNS | Enables the Domain Name System (DNS) for service on this TCP/IP-bound network adapter.
EnableIPFilterSec | Enables IP security globally across all IP-bound network adapters.
EnableIPSec | Enables IP security on this specific TCP/IP-enabled network adapter.
EnableStatic | Enables static TCP/IP addressing for the target network adapter.
EnableWINS | Enables WINS settings specific to TCP/IP, but independent of the network adapter.
ReleaseDHCPLease | Releases the IP address bound to a specific DHCP-enabled network adapter.
ReleaseDHCPLeaseAll | Releases the IP addresses bound to all DHCP-enabled network adapters.
RenewDHCPLease | Renews the IP address on specific DHCP-enabled network adapters.
RenewDHCPLeaseAll | Renews the IP addresses on all DHCP-enabled network adapters.
SetArpAlwaysSourceRoute | Sets the transmission of ARP queries by the TCP/IP.
SetArpUseEtherSNAP | Enables Ethernet packets to use 802.3 SNAP encoding.
SetDatabasePath | Sets the path to the standard Internet database files (HOSTS, LMHOSTS, NETWORKS, and PROTOCOLS).
SetDeadGWDetect | Enables dead gateway detection.
SetDefaultTOS | Obsolete. This method sets the default Type of Service (TOS) value in the header of outgoing IP packets.
SetDefaultTTL | Sets the default Time to Live (TTL) value in the header of outgoing IP packets. SetDNSDomain Sets the DNS domain. SetDNSServerSearchOrder Sets the server search order as an array of elements. SetDNSSuffixSearchOrder Sets the suffix search order as an array of elements. SetDynamicDNSRegistration Indicates dynamic DNS registration of IP addresses for this IP-bound adapter. This method is new for Windows XP. SetForwardBufferMemory Specifies how much memory IP allocates to store packet data in the router packet queue. SetGateways Specifies a list of gateways for routing packets destined for a different subnet than the one this adapter is connected to. SetIGMPLevel Sets the extent to which the system supports IP multicasting and participates in the Internet Group Management Protocol. SetIPConnectionMetric Sets the routing metric associated with this IP-bound adapter. Windows 2000 SP2 and earlier and Windows NT: This method is not available. SetIPUseZeroBroadcast Sets IP zero broadcast usage. SetIPXFrameTypeNetworkPairs Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this method is obsolete. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Sets IPX network number or frame pairs for this network adapter. SetIPXVirtualNetworkNumber Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this method is obsolete. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Sets the Internetwork Packet Exchange (IPX) virtual network number on the target computer system. SetKeepAliveInterval Sets the interval separating Keep Alive Retransmissions until a response is received. SetKeepAliveTime Sets how often TCP attempts to verify that an idle connection is still available by sending a Keep Alive packet. SetMTU Sets the default Maximum Transmission Unit (MTU) for a network interface. This method is not supported. SetNumForwardPackets Sets the number of IP packet headers allocated for the router packet queue. SetPMTUBHDetect Enables detection of Black Hole routers. SetPMTUDiscovery Enables Maximum Transmission Unit (MTU) discovery. SetTcpipNetbios Sets the default operation of NetBIOS over TCP/IP. Windows 2000 and Windows NT 4.0: This property is not available. SetTcpMaxConnectRetransmissions Sets the number of attempts TCP will retransmit a connect request before aborting. SetTcpMaxDataRetransmissions Sets the number of times TCP will retransmit an individual data segment before aborting the connection. SetTcpNumConnections Sets the maximum number of connections that TCP may have open simultaneously. SetTcpUseRFC1122UrgentPointer Specifies whether TCP uses the RFC 1122 specification for urgent data, or the mode used by Berkeley Software Design (BSD) derived systems. SetTcpWindowSize Sets the maximum TCP Receive Window size offered by the system. SetWINSServer Sets the primary and secondary Windows Internet Naming Service (WINS) servers on this TCP/IP-bound network adapter.

Свойства

ArpAlwaysSourceRoute Data type: boolean Access type: Read-only If TRUE, TCP/IP transmits Address Resolution Protocol (ARP) queries with source routing enabled on Token Ring networks. By default (FALSE), ARP first queries without source routing, and then retries with source routing enabled if no reply is received. Source routing allows the routing of network packets across different types of networks. ArpUseEtherSNAP Data type: boolean Access type: Read-only If TRUE, Ethernet packets follow the IEEE 802.3 Sub-Network Access Protocol (SNAP) encoding. Setting this parameter to 1 forces TCP/IP to transmit Ethernet packets by using 802.3 SNAP encoding. By default (FALSE), the stack transmits packets in DIX Ethernet format. Windows 2000 and Windows NT systems can receive both formats.
Caption
Короткое описание объекта (в одну строчку). Только для чтения.
DatabasePath
Data type: string Access type: Read-only Valid Windows file path to standard Internet database files (HOSTS, LMHOSTS, NETWORKS, and PROTOCOLS). The file path is used by the Windows Sockets interface. This property is only available on computer systems running Windows 2000 and Windows NT. DeadGWDetectEnabled Data type: boolean If TRUE, dead gateway detection occurs. With this feature enabled, Transmission Control Protocol (TCP) asks Internet Protocol (IP) to change to a backup gateway if it retransmits a segment several times without receiving a response. DefaultIPGateway Data type: string array Access type: Read-only Array of IP addresses of default gateways that the computer system uses. Example: "192.168.12.1 192.168.46.1" DefaultTOS Data type: uint8 Access type: Read-only Default Type Of Service (TOS) value set in the header of outgoing IP packets. Request for Comments (RFC) 791 defines the values. Default: 0 (zero), Valid Range: 0 - 255. DefaultTTL Data type: uint8 Access type: Read-only Default Time To Live (TTL) value set in the header of outgoing IP packets. The TTL specifies the number of routers an IP packet can pass through to reach its destination before being discarded. Each router decrements by one the TTL count of a packet as it passes through and discards the packets—if the TTL is 0 (zero). Default: 32, Valid Range: 1 - 255.
Description
Описание объекта CIM_Setting. Только для чтения
DHCPEnabled
Data type: boolean Access type: Read-only If TRUE, the dynamic host configuration protocol (DHCP) server automatically assigns an IP address to the computer system when establishing a network connection. DHCPLeaseExpires Data type: datetime Access type: Read-only Expiration date and time for a leased IP address that was assigned to the computer by the dynamic host configuration protocol (DHCP) server. Example: 20521201000230.000000000 DHCPLeaseObtained Data type: datetime Access type: Read-only Date and time the lease was obtained for the IP address assigned to the computer by the dynamic host configuration protocol (DHCP) server. Example: 19521201000230.000000000 DHCPServer Data type: string Access type: Read-only IP address of the dynamic host configuration protocol (DHCP) server. Example: "10.55.34.2" DNSDomain Data type: string Access type: Read-only Organization name followed by a period and an extension that indicates the type of organization, such as microsoft.com. The name can be any combination of the letters A through Z, the numerals 0 through 9, and the hyphen (-), plus the period (.) character used as a separator. Example: "microsoft.com" DNSDomainSuffixSearchOrder Data type: string array Access type: Read-only Array of DNS domain suffixes to be appended to the end of host names during name resolution. When attempting to resolve a fully-qualified domain name (FQDN) from a host-only name, the system will first append the local domain name. If this is not successful, the system will use the domain suffix list to create additional FQDNs in the order listed and query DNS servers for each. Example: "samples.microsoft.com example.microsoft.com" DNSEnabledForWINSResolution Data type: boolean Access type: Read-only If TRUE, the Domain Name System (DNS) is enabled for name resolution over Windows Internet Naming Service (WINS) resolution. If the name cannot be resolved using DNS, the name request is forwarded to WINS for resolution. DNSHostName Data type: string Access type: Read-only Host name used to identify the local computer for authentication by some utilities. Other TCP/IP-based utilities can use this value to acquire the name of the local computer. Host names are stored on DNS servers in a table that maps names to IP addresses for use by DNS. The name can be any combination of the letters A through Z, the numerals 0 through 9, and the hyphen (-), plus the period (.) character used as a separator. By default, this value is the Microsoft networking computer name, but the network administrator can assign another host name without affecting the computer name. Example: "corpdns" DNSServerSearchOrder Data type: string array Access type: Read-only Array of server IP addresses to be used in querying for DNS servers. DomainDNSRegistrationEnabled Data type: boolean Access type: Read-only If TRUE, the IP addresses for this connection are registered in DNS under the domain name of this connection in addition to being registered under the computer's full DNS name. The domain name of this connection is either set using the SetDNSDomain() method or assigned by DSCP. The registered name is the host name of the computer with the domain name appended. Windows 2000 and Windows NT 4.0: This property is not available. ForwardBufferMemory Data type: uint32 Access type: Read-only Qualifiers: Units(Bytes) Memory allocated by IP to store packet data in the router packet queue. When this buffer space is filled, the router begins discarding packets at random from its queue. Packet queue data buffers are 256 bytes in length, so the value of this parameter should be a multiple of 256. Multiple buffers are chained together for larger packets. The IP header for a packet is stored separately. This parameter is ignored and no buffers are allocated if the IP router is not enabled. The buffer size can range from the network MTU to a value smaller than 0xFFFFFFFF. Default: 74240 (fifty 1480-byte packets, rounded to a multiple of 256). FullDNSRegistrationEnabled Data type: boolean Access type: Read-only If TRUE, the IP addresses for this connection are registered in DNS under the computer's full DNS name. The full DNS name of the computer is displayed on the Network Identification tab in the System application in Control Panel. Windows 2000 and Windows NT 4.0: This property is not available. GatewayCostMetric Data type: uint16 array Access type: Read-only Array of integer cost metric values (ranging from 1 to 9999) to be used in calculating the fastest, most reliable, or least expensive routes. This argument has a one-to-one correspondence with the DefaultIPGateway property. Windows NT 4.0: This property is not available. IGMPLevel Data type: uint8 Access type: Read-only Extent to which the system supports IP multicast and participates in the Internet Group Management Protocol (IGMP). At level 0 (zero), the system provides no multicast support. At level 1, the system may only send IP multicast packets. At level 2, the system may send IP multicast packets and fully participate in IGMP to receive multicast packets. Value Meaning 0 No Multicast 1 IP Multicast 2 IP and IGMP Multicast (default) Index Data type: uint32 Access type: Read-only Qualifiers: Key Index number of the Windows network adapter configuration. The index number is used when there is more than one configuration available. InterfaceIndex Data type: uint32 Access type: Read-only Index value that uniquely identifies a local network interface. The value in this property is the same as the value in the InterfaceIndex property in the instance of Win32_IP4RouteTable that represents the network interface in the route table. Windows XP, Windows 2000, and Windows NT 4.0: This property is not available. IPAddress Data type: string array Access type: Read-only Array of all of the IP addresses associated with the current network adapter. Starting with Windows Vista, this property can contain either IPv6 addresses or IPv4 addresses. For more information, see IPv6 and IPv4 Support in WMI. Example IPv6 address: "2010:836B:4179::836B:4179" Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property contains addresses in IPv4 format. Example: "172.16.22.0" IPConnectionMetric Data type: uint32 Access type: Read-only Cost of using the configured routes for the IP bound adapter and is the weighted value for those routes in the IP routing table. If there are multiple routes to a destination in the IP routing table, the route with the lowest metric is used. The default value is 1. Windows 2000 and Windows NT 4.0: This property is not available. IPEnabled Data type: boolean Access type: Read-only If TRUE, TCP/IP is bound and enabled on this network adapter. IPFilterSecurityEnabled Data type: boolean Access type: Read-only If TRUE, IP port security is enabled globally across all IP-bound network adapters and the security values associated with individual network adapters are in effect. This property is used in conjunction with IPSecPermitTCPPorts, IPSecPermitUDPPorts, and IPSecPermitIPProtocols. If FALSE, IP filter security is disabled across all network adapters and allows all port and protocol traffic to flow unfiltered. IPPortSecurityEnabled Data type: boolean Access type: Read-only Qualifiers: Deprecated If TRUE, IP port security is enabled globally across all IP-bound network adapters. This property is obsolete. In place of this property, you should use IPFilterSecurityEnabled. IPSecPermitIPProtocols Data type: string array Access type: Read-only Array of the protocols permitted to run over the IP. The list of protocols is defined using the EnableIPSec method. The list will either be empty or contain numeric values. A numeric value of 0 (zero) indicates access permission is granted for all protocols. An empty string indicates that no protocols are permitted to run when IPFilterSecurityEnabled is TRUE. IPSecPermitTCPPorts Data type: string array Access type: Read-only Array of the ports that will be granted access permission for TCP. The list of protocols is defined using the EnableIPSec method. The list will either be empty or contain numeric values. A numeric value of 0 (zero)indicates access permission is granted for all ports. An empty string indicates that no ports are granted access permission when IPFilterSecurityEnabled is TRUE. IPSecPermitUDPPorts Data type: string array Access type: Read-only Array of the ports that will be granted User Datagram Protocol (UDP) access permission. The list of protocols is defined using the EnableIPSec method. The list will either be empty or contain numeric values. A numeric value of 0 (zero) indicates access permission is granted for all ports. An empty string indicates that no ports are granted access permission when IPFilterSecurityEnabled is TRUE. IPSubnet Data type: string array Access type: Read-only Array of all of the subnet masks associated with the current network adapter. Example: "255.255.0.0" IPUseZeroBroadcast Data type: boolean Access type: Read-only If TRUE, IP zeros-broadcasts are used (0.0.0.0), and the system uses ones-broadcasts (255.255.255.255). Computer systems generally use ones-broadcasts, but those derived from BSD implementations use zeros-broadcasts. Systems that do not use that same broadcasts will not interoperate on the same network. The default is FALSE. IPXAddress Data type: string Access type: Read-only Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this property does not contain useful data. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Internetwork Packet Exchange (IPX) address of the network adapter. The IPX address identifies a computer system on a network using the IPX protocol. IPXEnabled Data type: boolean Access type: Read-only Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this property does not contain useful data. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: If TRUE, the or Internetwork Packet Exchange (IPX) protocol is bound and enabled for this adapter. IPXFrameType Data type: uint32 array Access type: Read-only Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this property does not contain useful data. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Array of frame-type identifiers. The values in this array correspond to the elements in IPXNetworkNumber. Value Meaning 0 Ethernet II 1 Ethernet 802.3 2 Ethernet 802.2 3 Ethernet SNAP 255 AUTO IPXMediaType Data type: uint32 Access type: Read-only Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this property does not contain useful data. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Internetwork Packet Exchange (IPX) media-type identifier. Value Meaning 1 Ethernet 2 Token Ring 3 FDDI 8 ARCNET IPXNetworkNumber Data type: string array Access type: Read-only Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this property does not contain useful data. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Array of characters that uniquely identifies a frame or network adapter combination on the computer system. The NetWare Link (NWLink) IPX/SPX-compatible transport in Windows 2000 and Windows NT 4.0 and later use two distinctly different types of network numbers. This number is sometimes referred to as the external network number. It must be unique for each network segment. The order in this string list will correspond item-for-item with the elements in the IPXFrameType property. IPXVirtualNetNumber Data type: string Access type: Read-only Starting with Windows Vista, the Internetwork Packet Exchange (IPX) technology is no longer supported and this property does not contain useful data. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Unique identifier of the computer system on the network. It is represented in the form of an eight-character hexadecimal digit. Windows 2000 and Windows NT use the virtual network number (also known as an internal network number) for internal routing. KeepAliveInterval Data type: uint32 Access type: Read-only Qualifiers: Units(Milliseconds) Interval separating Keep Alive Retransmissions until a response is received. After a response is received, the delay until the next Keep Alive Transmission is again controlled by the value of KeepAliveTime. The connection will be aborted after the number of retransmissions specified by TcpMaxDataRetransmissions have gone unanswered. Default: 1000, Valid Range: 1 - 0xFFFFFFFF. KeepAliveTime Data type: uint32 Access type: Read-only Qualifiers: Units(Milliseconds) The KeepAliveTime property indicates how often the TCP attempts to verify that an idle connection is still intact by sending a Keep Alive Packet. A remote system that is reachable will acknowledge the keep alive transmission. Keep Alive packets are not sent by default. This feature may be enabled in a connection by an application. Default: 7,200,000 (two hours). MACAddress Data type: string Access type: Read-only Media Access Control (MAC) address of the network adapter. A MAC address is assigned by the manufacturer to uniquely identify the network adapter. Example: "00:80:C7:8F:6C:96" MTU Data type: uint32 Access type: Read-only Qualifiers: Units(Bytes) Overrides the default Maximum Transmission Unit (MTU) for a network interface. The MTU is the maximum packet size (including the transport header) that the transport will transmit over the underlying network. The IP datagram can span multiple packets. The range of this value spans the minimum packet size (68) to the MTU supported by the underlying network. NumForwardPackets Data type: uint32 Access type: Read-only Number of IP packet headers allocated for the router packet queue. When all headers are in use, the router will begin to discard packets from the queue at random. This value should be at least as large as the ForwardBufferMemory value divided by the maximum IP data size of the networks connected to the router. It should be no larger than the ForwardBufferMemory value divided by 256, since at least 256 bytes of forward buffer memory are used for each packet. The optimal number of forward packets for a given ForwardBufferMemory size depends on the type of traffic on the network. It will be somewhere between these two values. If the router is not enabled, this parameter is ignored and no headers are allocated. Default: 50, Valid Range: 1 - 0xFFFFFFFE. PMTUBHDetectEnabled Data type: boolean Access type: Read-only If TRUE, detection of black hole routers occurs while TCP discovers the path of the Maximum Transmission Unit. A black hole router does not return ICMP Destination Unreachable messages when it needs to fragment an IP datagram with the Don't Fragment bit set. TCP depends on receiving these messages to perform Path MTU Discovery. With this feature enabled, TCP will try to send segments without the Don't Fragment bit set if several retransmissions of a segment go unacknowledged. If the segment is acknowledged as a result, the MSS will be decreased and the Don't Fragment bit will be set in future packets on the connection. Enabling black hole detection increases the maximum number of retransmissions performed for a given segment. The default value of this property is FALSE. PMTUDiscoveryEnabled Data type: boolean Access type: Read-only If TRUE, the Maximum Transmission Unit (MTU) path is discovered over the path to a remote host. By discovering the MTU path and limiting TCP segments to this size, TCP can eliminate fragmentation at routers along the path that connect networks with different MTUs. Fragmentation adversely affects TCP throughput and network congestion. Setting this parameter to FALSE causes an MTU of 576 bytes to be used for all connections that are not to machines on the local subnet. The default is TRUE. ServiceName Data type: string Access type: Read-only Service name of the network adapter. This name is usually shorter than the full product name. Example: "Elnkii" SettingID Data type: string Access type: Read-only Identifier by which the CIM_Setting object is known. This property is inherited from CIM_Setting. TcpipNetbiosOptions Data type: uint32 Access type: Read-only Bitmap of the possible settings related to NetBIOS over TCP/IP. Windows 2000 and Windows NT 4.0: This property is not available. Values are identified in the following table. Value (Dec/Hex) Meaning 0 0x0 EnableNetbiosViaDhcp 1 0x1 EnableNetbios 2 0x2 DisableNetbios TcpMaxConnectRetransmissions Data type: uint32 Access type: Read-only Number of times TCP attempts to retransmit a Connect Request before terminating the connection. The initial retransmission timeout is 3 seconds. The retransmission timeout doubles for each attempt. Default: 3, Valid Range: 0 - 0xFFFFFFFF. TcpMaxDataRetransmissions Data type: uint32 Access type: Read-only Number of times TCP retransmits an individual data segment (nonconnect segment) before terminating the connection. The retransmission timeout doubles with each successive retransmission on a connection. Default: 5, Valid Range: 0 - 0xFFFFFFFF. TcpNumConnections Data type: uint32 Access type: Read-only Maximum number of connections that TCP can have open simultaneously. Default: 0xFFFFFE, Valid Range: 0 - 0xFFFFFE. TcpUseRFC1122UrgentPointer Data type: boolean Access type: Read-only If TRUE, TCP uses the RFC 1122 specification for urgent data. If FALSE (default), TCP uses the mode used by Berkeley Software Design (BSD) derived systems. The two mechanisms interpret the urgent pointer differently and are not interoperable. The default value is TRUE. TcpWindowSize Data type: uint16 Access type: Read-only Qualifiers: Units(Bytes) Maximum TCP Receive Window size offered by the system. The Receive Window specifies the number of bytes a sender may transmit without receiving an acknowledgment. In general, larger receiving windows will improve performance over high-delay and high-bandwidth networks. For efficiency, the receiving window should be an even multiple of the TCP Maximum Segment Size (MSS). Default: Four times the maximum TCP data size or an even multiple of TCP data size rounded up to the nearest multiple of 8192. Ethernet networks default to 8760. Valid range: 0 - 65535. WINSEnableLMHostsLookup Data type: boolean Access type: Read-only If TRUE, local lookup files are used. Lookup files will contain a map of IP addresses to host names. If they exist on the local system, they will be found in %SystemRoot%\system32\drivers\etc. WINSHostLookupFile Data type: string Access type: Read-only Path to a WINS lookup file on the local system. This file will contain a map of IP addresses to host names. If the file specified in this property is found, it will be copied to the %SystemRoot%\system32\drivers\etc folder of the local system. Valid only if the WINSEnableLMHostsLookup property is TRUE. WINSPrimaryServer Data type: string Access type: Read-only IP address for the primary WINS server. WINSScopeID Data type: string Access type: Read-only Value appended to the end of the NetBIOS name that isolates a group of computer systems communicating with only each other. It is used for all NetBIOS transactions over TCP/IP communications from that computer system. Computers configured with identical scope identifiers are able to communicate with this computer. TCP/IP clients with different scope identifiers disregard packets from computers with this scope identifier. Valid only when the EnableWINS method executes successfully. WINSSecondaryServer Data type: string Access type: Read-only IP address for the secondary WINS server.

Примечания

Класс Win32_NetworkAdapterConfiguration наследует от CIM_Setting.

Пример

Пример с применением сценария VBS

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" _
    & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration",,48)
For Each objItem in colItems
    Wscript.Echo "-----------------------------------"
    Wscript.Echo "Win32_NetworkAdapterConfiguration instance"
    Wscript.Echo "-----------------------------------"
    Wscript.Echo "ArpAlwaysSourceRoute: " _
        & objItem.ArpAlwaysSourceRoute
    Wscript.Echo "ArpUseEtherSNAP: " & objItem.ArpUseEtherSNAP
    Wscript.Echo "DatabasePath: " & objItem.DatabasePath
    Wscript.Echo "DeadGWDetectEnabled: " _
        & objItem.DeadGWDetectEnabled
    Wscript.Echo "DefaultIPGateway: " & strDefaultIPGateway
    Wscript.Echo "DefaultTOS: " & objItem.DefaultTOS
    Wscript.Echo "DefaultTTL: " & objItem.DefaultTTL
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "DHCPEnabled: " & objItem.DHCPEnabled
    Wscript.Echo "DHCPLeaseExpires: " & objItem.DHCPLeaseExpires
    Wscript.Echo "DHCPLeaseObtained: " & objItem.DHCPLeaseObtained
    Wscript.Echo "DHCPServer: " & objItem.DHCPServer
    Wscript.Echo "DNSDomain: " & objItem.DNSDomain
    Wscript.Echo "DNSDomainSuffixSearchOrder: " _
        & strDNSDomainSuffixSearchOrder
    Wscript.Echo "DNSEnabledForWINSResolution: " _
        & objItem.DNSEnabledForWINSResolution
    Wscript.Echo "DNSHostName: " & objItem.DNSHostName
    Wscript.Echo "DNSServerSearchOrder: " _
        & strDNSServerSearchOrder
    Wscript.Echo "DomainDNSRegistrationEnabled: " _
        & objItem.DomainDNSRegistrationEnabled
    Wscript.Echo "ForwardBufferMemory: " _
        & objItem.ForwardBufferMemory
    Wscript.Echo "FullDNSRegistrationEnabled: " _
        & objItem.FullDNSRegistrationEnabled
    Wscript.Echo "GatewayCostMetric: " & strGatewayCostMetric
    Wscript.Echo "IGMPLevel: " & objItem.IGMPLevel
    Wscript.Echo "Index: " & objItem.Index
    Wscript.Echo "IPAddress: " & strIPAddress
    Wscript.Echo "IPConnectionMetric: " _
        & objItem.IPConnectionMetric
    Wscript.Echo "IPEnabled: " & objItem.IPEnabled
    Wscript.Echo "IPFilterSecurityEnabled: " _
        & objItem.IPFilterSecurityEnabled
    Wscript.Echo "IPPortSecurityEnabled: " _
        & objItem.IPPortSecurityEnabled
    Wscript.Echo "IPSecPermitIPProtocols: " _
        & strIPSecPermitIPProtocols
    Wscript.Echo "IPSecPermitTCPPorts: " _
        & strIPSecPermitTCPPorts
    Wscript.Echo "IPSecPermitUDPPorts: " _
        & strIPSecPermitUDPPorts
    Wscript.Echo "IPSubnet: " & strIPSubnet
    Wscript.Echo "IPUseZeroBroadcast: " _
        & objItem.IPUseZeroBroadcast
    Wscript.Echo "IPXAddress: " & objItem.IPXAddress
    Wscript.Echo "IPXEnabled: " & objItem.IPXEnabled
    Wscript.Echo "IPXFrameType: " & strIPXFrameType
    Wscript.Echo "IPXNetworkNumber: " & strIPXNetworkNumber
    Wscript.Echo "IPXVirtualNetNumber: " _
        & objItem.IPXVirtualNetNumber
    Wscript.Echo "KeepAliveInterval: " _
        & objItem.KeepAliveInterval
    Wscript.Echo "KeepAliveTime: " & objItem.KeepAliveTime
    Wscript.Echo "MACAddress: " & objItem.MACAddress
    Wscript.Echo "MTU: " & objItem.MTU
    Wscript.Echo "NumForwardPackets: " _
        & objItem.NumForwardPackets
    Wscript.Echo "PMTUBHDetectEnabled: " _
        & objItem.PMTUBHDetectEnabled
    Wscript.Echo "PMTUDiscoveryEnabled: " _
        & objItem.PMTUDiscoveryEnabled
    Wscript.Echo "ServiceName: " & objItem.ServiceName
    Wscript.Echo "SettingID: " & objItem.SettingID
    Wscript.Echo "TcpipNetbiosOptions: " _
        & objItem.TcpipNetbiosOptions
    Wscript.Echo "TcpMaxConnectRetransmissions: " _
        & objItem.TcpMaxConnectRetransmissions
    Wscript.Echo "TcpMaxDataRetransmissions: " _
        & objItem.TcpMaxDataRetransmissions
    Wscript.Echo "TcpNumConnections: " _
        & objItem.TcpNumConnections
    Wscript.Echo "TcpUseRFC1122UrgentPointer: " _
        & objItem.TcpUseRFC1122UrgentPointer
    Wscript.Echo "TcpWindowSize: " & objItem.TcpWindowSize
    Wscript.Echo "WINSEnableLMHostsLookup: " _
        & objItem.WINSEnableLMHostsLookup
    Wscript.Echo "WINSHostLookupFile: " _
        & objItem.WINSHostLookupFile
    Wscript.Echo "WINSPrimaryServer: " _
        & objItem.WINSPrimaryServer
    Wscript.Echo "WINSScopeID: " & objItem.WINSScopeID
    Wscript.Echo "WINSSecondaryServer: " _
        & objItem.WINSSecondaryServer
Next

Ниже показан сценарий, который осуществляет поиск всех сетевых адаптеров с поддержкой TCP/IP, контролирует, включен ли DHCP на каждом адаптере и, если нет, включает его.
strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled = 'True'")

For Each objItem in colItems
    If objItem.DHCPEnabled = False Then
        Wscript.Echo objItem.Caption
        intReturn = objItem.EnableDHCP
        Select Case intReturn
            Case 0
                Wscript.Echo "DHCP enabled"
            Case 1
                Wscript.Echo "You must reboot before DHCP will be enabled"
            Case Else
                Wscript.Echo "Error occurred"
        End Select
        Wscript.Echo
    End If
Next

Вы также можете отключить DHCP; для этого необходимо настроить статический IP-адрес и маску подсети в адаптере.

*** Настройка IP-адреса ***

arrIPAddress = Array("192.168.0.12")
arrSubnetMask = Array("255.255.255.0")

strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled = 'True'")

For Each objItem in colItems
    If objItem.DHCPEnabled = True Then
        Wscript.Echo objItem.Caption
        intReturn = objItem.EnableStatic(arrIPAddress, arrSubnetMask)
        Select Case intReturn
            Case 0
                Wscript.Echo "Static address assigned"
            Case 1
                Wscript.Echo "You must reboot before the static address will take effect"
            Case Else
                Wscript.Echo "Error occurred"
        End Select
        Wscript.Echo
    End If
Next

[VB.NET]
Imports System
Imports System.Management
Imports System.Windows.Forms

Namespace WMISample

    Public Class MyWMIQuery

        Public Overloads Shared Function Main() As Integer

            Try
                Dim searcher As New ManagementObjectSearcher( _
                    "root\CIMV2", _
                    "SELECT * FROM Win32_NetworkAdapterConfiguration")

                For Each queryObj As ManagementObject in searcher.Get()

                    Console.WriteLine("-----------------------------------")

                    Console.WriteLine("Win32_NetworkAdapterConfiguration instance")

                    Console.WriteLine("-----------------------------------")

                    If queryObj("IPAddress") Is Nothing Then
                        Console.WriteLine("IPAddress: {0}", queryObj("IPAddress"))
                    Else
                        Dim arrIPAddress As String()
                        arrIPAddress = queryObj("IPAddress")

                        For Each arrValue As String In arrIPAddress
                            Console.WriteLine("IPAddress: {0}", arrValue)
                        Next
                    End If
                Next

            Catch err As ManagementException

                MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)

            End Try
        End Function
    End Class
End Namespace

VB.NET
' Перечисление всех адаптеров
Option Strict On
Option Explicit On

Imports System
Imports System.Management

Public Class ConsoleApp

   Shared Sub Main
      Network.EnumNetworkAdapters()
   End Sub

End Class

Public Class Network
   Public Shared Sub EnumNetworkAdapters()
      Dim query as ManagementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration")
      Dim queryCollection as ManagementObjectCollection  = query.Get()
      Dim mo as ManagementObject
      Dim s as String

      for each mo in queryCollection
           Console.WriteLine( "'{0}'", mo.ClassPath)
           Console.WriteLine( "'{0}'", mo.Options)
           Console.WriteLine( "Index   '{0}'", mo("Index"))
           Console.WriteLine( "Description   '{0}'", mo("Description"))
           Console.WriteLine( "MacAddress   '{0}'", mo("MacAddress"))

           if(CType(mo("IPEnabled"), Boolean) = true)
               dim addresses() as string = CType(mo("IPAddress"), String())
               dim subnets() as string = CType(mo("IPSubnet"), String())

               Console.WriteLine( "DNS Host   '{0}'", mo("DNSHostName"))
               Console.WriteLine( "DNS Domain   '{0}'", mo("DNSDomain"))

               for each s in addresses
                   Console.WriteLine( "IP Address   '{0}'", s)
               next

               for each s in subnets
                   Console.WriteLine( "IP Subnet   '{0}'", s)
               next
           end if
      next
   End Sub
End Class

[C#]
using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT * FROM Win32_NetworkAdapterConfiguration");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_NetworkAdapterConfiguration instance");
                    Console.WriteLine("-----------------------------------");

                    if(queryObj["IPAddress"] == null)
                        Console.WriteLine("IPAddress: {0}", queryObj["IPAddress"]);
                    else
                    {
                        String[] arrIPAddress = (String[])(queryObj["IPAddress"]);

                        foreach (String arrValue in arrIPAddress)
                        {
                            Console.WriteLine("IPAddress: {0}", arrValue);
                        }
                    }
                }
            }

            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

[JScript]

var wbemFlagReturnImmediately = 0x10;

var wbemFlagForwardOnly = 0x20;

var strComputer = ".";

   var objWMIService = GetObject("winmgmts:\\\\" + strComputer + "\\root\\CIMV2");

   var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly);

    var enumItems = new Enumerator(colItems);

   for (; !enumItems.atEnd(); enumItems.moveNext()) {
      var objItem = enumItems.item();

      WScript.Echo("-----------------------------------");

      WScript.Echo("Win32_NetworkAdapterConfiguration instance");

      WScript.Echo("-----------------------------------");

      try { WScript.Echo("IPAddress: " + (objItem.IPAddress.toArray()).join(",")); }
         catch(e) { WScript.Echo("IPAddress: null"); }

   }

[WMIC]

wmic nicconfig get IPAddress /value

Смотри также

Computer System Hardware Classes


Win32_OperatingSystem

Класс Win32_OperatingSystem содержит информацию об операционной системе семейства Windows, установленной на компьютере.

Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Если компьютер имеет несколько операционных систем, то данный класс возвращает информацию о текущей активной операционной системе.

class Win32_OperatingSystem : CIM_OperatingSystem
{
  string BootDevice;
  string BuildNumber;
  string BuildType;
  string Caption;
  string CodeSet;
  string CountryCode;
  string CreationClassName;
  string CSCreationClassName;
  string CSDVersion;
  string CSName;
  sint16 CurrentTimeZone;
  boolean DataExecutionPrevention_Available;
  boolean DataExecutionPrevention_32BitApplications;
  boolean DataExecutionPrevention_Drivers;
  uint8 DataExecutionPrevention_SupportPolicy;
  boolean Debug;
  string Description;
  boolean Distributed;
  uint32 EncryptionLevel;
  uint8 ForegroundApplicationBoost;
  uint64 FreePhysicalMemory;
  uint64 FreeSpaceInPagingFiles;
  uint64 FreeVirtualMemory;
  datetime InstallDate;
  uint32 LargeSystemCache;
  datetime LastBootUpTime;
  datetime LocalDateTime;
  string Locale;
  string Manufacturer;
  uint32 MaxNumberOfProcesses;
  uint64 MaxProcessMemorySize;
  string MUILanguages[];
  string Name;
  uint32 NumberOfLicensedUsers;
  uint32 NumberOfProcesses;
  uint32 NumberOfUsers;
  uint32 OperatingSystemSKU;
  string Organization;
  string OSArchitecture;
  uint32 OSLanguage;
  uint32 OSProductSuite;
  uint16 OSType;
  string OtherTypeDescription;
  Boolean PAEEnabled;
  string PlusProductID;
  string PlusVersionNumber;
  boolean Primary;
  uint32 ProductType;
  uint8 QuantumLength;
  uint8 QuantumType;
  string RegisteredUser;
  string SerialNumber;
  uint16 ServicePackMajorVersion;
  uint16 ServicePackMinorVersion;
  uint64 SizeStoredInPagingFiles;
  string Status;
  uint32 SuiteMask;
  string SystemDevice;
  string SystemDirectory;
  string SystemDrive;
  uint64 TotalSwapSpaceSize;
  uint64 TotalVirtualMemorySize;
  uint64 TotalVisibleMemorySize;
  string Version;
  string WindowsDirectory;
};

Методы

Метод | Описание
Reboot | Перезагружает систему
SetDateTime | Устанавливает дату и время на компьютере
Shutdown | Выгружает программы и библиотеки DLL и выключает компьютер
Win32Shutdown | Обеспечивает все возможности выключения компьютера, поддерживаемые операционной системой Windows
Win32ShutdownTracker | Provides the same set of shutdown options supported by the Win32Shutdown method in Win32_OperatingSystem, but also allows you to specify comments, a reason for shutdown, or a timeout. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Этот метод не доступен

Свойства

BootDevice
Только для чтения. Имя диска, с которого стартует Windows . Например, "\\Device\Harddisk0"
BuildNumber
Только для чтения. Build number of an operating system. It can be used for more precise version information than product release version numbers. Example: "1381"
BuildType
Только для чтения. Type of build used for an operating system. Examples: ""retail build"", ""checked build""
Caption
Только для чтения. Короткое описание объекта в одну строчку. Строка включает в себя версию OC, например, "Microsoft Windows XP Professional Version = 5.1.2500". Данное свойство может быть локализованным.
CodeSet
Только для чтения. Qualifiers: MaxLen(6) Code page value an operating system uses. A code page contains a character table that an operating system uses to translate strings for different languages. The American National Standards Institute (ANSI) lists values that represent defined code pages. If an operating system does not use an ANSI code page, this member is set to 0 (zero). The CodeSet string can use a maximum of six characters to define the code page value. Example: "1255"
CountryCode Data type: string Access type: Только для чтения Code for the country/region that an operating system uses. Values are based on international phone dialing prefixes—also referred to as IBM country/region codes. This property can use a maximum of six characters to define the country/region code value. Example: "1" (United States)
CreationClassName Data type: string Access type: Только для чтения Qualifiers: Key, MaxLen(256) Name of the first concrete class that appears in the inheritance chain used in the creation of an instance. When used with other key properties of the class, this property allows all instances of this class and its subclasses to be identified uniquely.
CSCreationClassName Data type: string Access type: Только для чтения Creation class name of the scoping computer system.
CSDVersion Data type: string Access type: Только для чтения NULL-terminated string that indicates the latest service pack installed on a computer. If no service pack is installed, the string is NULL. For computers running on Windows 95, this property contains a null-terminated string that provides more information about the operating system. Example: "Service Pack 3"
CSName Data type: string Access type: Только для чтения Name of the scoping computer system.
CurrentTimeZone Data type: sint16 Access type: Только для чтения Number, in minutes, an operating system is offset from Greenwich mean time (GMT). The number is positive, negative, or zero.
DataExecutionPrevention_32BitApplications Data type: boolean Access type: Только для чтения When the data execution prevention hardware feature is available, this property indicates that the feature is set to work for 32-bit applications if True. On 64-bit computers, the data execution prevention feature is configured in the Boot Configuration Data (BCD) store and the properties in Win32_OperatingSystem are set accordingly. Windows Server 2003, Windows 2000, Windows NT 4.0, Windows XP, and Windows Me/98/95: This property is not available. DataExecutionPrevention_Available Data type: boolean Access type: Только для чтения Data execution prevention is a hardware feature to prevent buffer overrun attacks by stopping the execution of code on data-type memory pages. If True, then this feature is available. On 64-bit computers, the data execution prevention feature is configured in the BCD store and the properties in Win32_OperatingSystem are set accordingly. Windows Server 2003, Windows 2000, Windows NT 4.0, Windows XP, and Windows Me/98/95: This property is not available. DataExecutionPrevention_Drivers Data type: boolean Access type: Только для чтения When the data execution prevention hardware feature is available, this property indicates that the feature is set to work for drivers if True. On 64-bit computers, the data execution prevention feature is configured in the BCD store and the properties in Win32_OperatingSystem are set accordingly. Windows Server 2003, Windows 2000, Windows NT 4.0, Windows XP, and Windows Me/98/95: This property is not available. DataExecutionPrevention_SupportPolicy Data type: uint8 Indicates which Data Execution Prevention (DEP) setting is applied. The DEP setting specifies the extent to which DEP applies to 32-bit applications on the system. DEP is always applied to the Windows kernel. Windows Server 2003, Windows 2000, Windows NT 4.0, Windows XP, and Windows Me/98/95: This property is not available. The following table lists the possible values. Value Meaning Always Off 0 DEP is turned off for all 32-bit applications on the computer with no exceptions. This setting is not available for the user interface. Always On 1 DEP is enabled for all 32-bit applications on the computer. This setting is not available for the user interface. Opt In 2 DEP is enabled for a limited number of binaries, the kernel, and all Windows-based services. However, it is off by default for all 32-bit applications. A user or administrator must explicitly choose either the AlwaysOn or the OptOut setting before DEP can be applied to 32-bit applications. Opt Out 3 DEP is enabled by default for all 32-bit applications. A user or administrator can explicitly remove support for a 32-bit application by adding the application to an exceptions list.
Debug Data type: boolean Access type: Только для чтения Operating system is a checked (debug) build. If True, the debugging version of User.exe is installed. Checked builds provide error checking, argument verification, and system debugging code. Additional code in a checked binary generates a kernel debugger error message and breaks into the debugger. This helps immediately determine the cause and location of the error. Performance may be affected in a checked build due to the additional code that is executed.
Description Data type: string Access type: Read/write Description of the Windows operating system. Some user interfaces for example, those that allow editing of this description, limit its length to 48 characters.
Distributed Data type: boolean Access type: Только для чтения If True, the operating system is distributed across several computer system nodes. If so, these nodes should be grouped as a cluster.
EncryptionLevel Data type: uint32 Access type: Только для чтения Windows Server 2003 and Windows XP: Encryption level for secure transactions: 40-bit, 128-bit, or n-bit.
ForegroundApplicationBoost Data type: uint8 Access type: Read/write Increase in priority is given to the foreground application. Application boost is implemented by giving an application more execution time slices (quantum lengths). Windows Me/98/95: Application boost is not available. A ForegroundApplicationBoost value of 0 (zero) indicates the system boosts the quantum length by 6; if 1, then 12; and if 2 then 18. The default value is 2. Windows NT 3.51 and earlier: Application boost is implemented by increasing the scheduling priority. The scheduling priority is increased by the value of this property. Value Meaning 0 None 1 Minimum 2 (Default) Maximum FreePhysicalMemory Data type: uint64 Access type: Только для чтения Number, in kilobytes, of physical memory currently unused and available. For more information about using uint64 values in scripts, see Scripting in WMI.
FreeSpaceInPagingFiles Data type: uint64 Access type: Только для чтения Number, in kilobytes, that can be mapped into the operating system paging files without causing any other pages to be swapped out. For more information about using uint64 values in scripts, see Scripting in WMI.
FreeVirtualMemory Data type: uint64 Access type: Только для чтения Number, in kilobytes, of virtual memory currently unused and available. For more information about using uint64 values in scripts, see Scripting in WMI.
InstallDate
Только для чтения. Дата установки ОС. Данное свойство не требует значения, указывающее на то, что ОС установлена.
LargeSystemCache Data type: uint32 Access type: Только для чтения Indicates whether to optimize memory for applications or system performance. Beginning with Windows Vista, this property is obsolete and not supported. Windows Server 2003 and Windows XP: This property is supported. Windows 2000 and Windows NT 4.0 SP4 and later: This property is not available. Value Meaning 0 Optimize memory for applications. 1 Optimize memory for system performance.
LastBootUpTime Data type: datetime Access type: Только для чтения Date and time the operating system was last restarted. LocalDateTime Data type: datetime Access type: Только для чтения Operating system version of the local date and time-of-day. Locale Data type: string Access type: Только для чтения Language identifier used by the operating system. A language identifier is a standard international numeric abbreviation for a country/region. Each language has a unique language identifier (LANGID), a 16-bit value that consists of a primary language identifier and a secondary language identifier.
Manufacturer Data type: string Access type: Только для чтения Name of the operating system manufacturer. For Windows-based systems, this value is "Microsoft Corporation". MaxNumberOfProcesses Data type: uint32 Access type: Только для чтения Maximum number of process contexts the operating system can support. The default value set by the provider is 4294967295 (0xFFFFFFFF). If there is no fixed maximum, the value should be 0 (zero). On systems that have a fixed maximum, this object can help diagnose failures that occur when the maximum is reached—if unknown, enter 4294967295 (0xFFFFFFFF). MaxProcessMemorySize Data type: uint64 Access type: Только для чтения Maximum number, in kilobytes, of memory that can be allocated to a process. For operating systems with no virtual memory, typically this value is equal to the total amount of physical memory minus the memory used by the BIOS and OS. For some operating systems, this value may be infinity, in which case 0 (zero) should be entered. In other cases, this value could be a constant, for example, 2G or 4G. For more information about using uint64 values in scripts, see Scripting in WMI.
MUILanguages Data type: string array Access type: Только для чтения Multilingual User Interface Pack (MUI Pack ) languages installed on the computer. For example, "en-us". MUI Pack languages are resource files that can be installed on the English version of the operating system. When an MUI Pack is installed, you can can change the user interface language to one of 33 supported languages.
Name Data type: string Access type: Только для чтения Operating system instance within a computer system.
NumberOfLicensedUsers Data type: uint32 Access type: Только для чтения Number of user licenses for the operating system. If unlimited, enter 0 (zero). If unknown, enter -1.
NumberOfProcesses Data type: uint32 Access type: Только для чтения Number of process contexts currently loaded or running on the operating system.
NumberOfUsers Data type: uint32 Access type: Только для чтения Number of user sessions for which the operating system is storing state information currently.
OperatingSystemSKU
номер Stock Keeping Unit (SKU) для операционной системы. Windows Server 2003, Windows XP, Windows 2000 и Windows NT 4.0: Это свойство не доступно. Возможные значения SKU. 18 Cluster Server Edition 19 Home Server Edition 20 Storage Express Server Edition 21 Storage Standard Server Edition 22 Storage Workgroup Server Edition 23 Storage Enterprise Server Edition 24 Server For Small Business Edition 25 Small Business Server Premium Edition
0 | Не определено
1 | Ultimate Edition
2 | Home Basic Edition
3 | Home Basic Premium Edition
4 | Enterprise Edition
5 | Home Basic N Edition
6 | Business Edition
7 | Standard Server Edition
8 | Datacenter Server Edition
9 | Small Business Server Edition
10 | Enterprise Server Edition
11 | Starter Edition
12 | Datacenter Server Core Edition
13 | Standard Server Core Edition
14 | Enterprise Server Core Edition
15 | Enterprise Server Edition for Itanium-Based Systems
16 | Business N Edition
17 | Web Server Edition
Organization
Только для чтения. Название компании для зарегистрированного пользователя операционной системы, например, "Microsoft Corporation"
OSArchitecture Data type: string Access type: Только для чтения Architecture of the operating system, as opposed to the processor. Example: 32-bit Windows Server 2003, Windows 2000, Windows NT 4.0, Windows XP, and Windows Me/98/95: This property is not available. OSLanguage Data type: uint32 Access type: Только для чтения Language version of the operating system installed. The following table lists the possible values. Example: 0x0807 (German, Switzerland). Value Meaning 1 0x1 Arabic 4 0x4 Chinese (Simplified)– China 9 0x9 English 1025 0x401 Arabic – Saudi Arabia 1026 0x402 Bulgarian 1027 0x403 Catalan 1028 0x404 Chinese (Traditional) – Taiwan 1029 0x405 Czech 1030 0x406 Danish 1031 0x407 German – Germany 1032 0x408 Greek 1033 0x409 English – United States 1034 0x40A Spanish – Traditional Sort 1035 0x40B Finnish 1036 0x40C French – France 1037 0x40D Hebrew 1038 0x40E Hungarian 1039 0x40F Icelandic 1040 0x410 Italian – Italy 1041 0x411 Japanese 1042 0x412 Korean 1043 0x413 Dutch – Netherlands 1044 0x414 Norwegian – Bokmal 1045 0x415 Polish 1046 0x416 Portuguese – Brazil 1047 0x417 Rhaeto-Romanic 1048 0x418 Romanian 1049 0x419 Russian 1050 0x41A Croatian 1051 0x41B Slovak 1052 0x41C Albanian 1053 0x41D Swedish 1054 0x41E Thai 1055 0x41F Turkish 1056 0x420 Urdu 1057 0x421 Indonesian 1058 0x422 Ukrainian 1059 0x423 Belarusian 1060 0x424 Slovenian 1061 0x425 Estonian 1062 0x426 Latvian 1063 0x427 Lithuanian 1065 0x429 Persian 1066 0x42A Vietnamese 1069 0x42D Basque 1070 0x42E Serbian 1071 0x42F Macedonian (FYROM) 1072 0x430 Sutu 1073 0x431 Tsonga 1074 0x432 Tswana 1076 0x434 Xhosa 1077 0x435 Zulu 1078 0x436 Afrikaans 1080 0x438 Faeroese 1081 0x439 Hindi 1082 0x43A Maltese 1084 0x43C Gaelic 1085 0x43D Yiddish 1086 0x43E Malay – Malaysia 2049 0x801 Arabic – Iraq 2052 0x804 Chinese (Simplified) – PRC 2055 0x807 German – Switzerland 2057 0x809 English – United Kingdom 2058 0x80A Spanish – Mexico 2060 0x80C French – Belgium 2064 0x810 Italian – Switzerland 2067 0x813 Dutch – Belgium 2068 0x814 Norwegian – Nynorsk 2070 0x816 Portuguese – Portugal 2072 0x818 Romanian – Moldova 2073 0x819 Russian – Moldova 2074 0x81A Serbian – Latin 2077 0x81D Swedish – Finland 3073 0xC01 Arabic – Egypt 3076 0xC04 Chinese (Traditional) – Hong Kong SAR 3079 0xC07 German – Austria 3081 0xC09 English – Australia 3082 0xC0A Spanish – International Sort 3084 0xC0C French – Canada 3098 0xC1A Serbian – Cyrillic 4097 0x1001 Arabic – Libya 4100 0x1004 Chinese (Simplified) – Singapore 4103 0x1007 German – Luxembourg 4105 0x1009 English – Canada 4106 0x100A Spanish – Guatemala 4108 0x100C French – Switzerland 5121 0x1401 Arabic – Algeria 5127 0x1407 German – Liechtenstein 5129 0x1409 English – New Zealand 5130 0x140A Spanish – Costa Rica 5132 0x140C French – Luxembourg 6145 0x1801 Arabic – Morocco 6153 0x1809 English – Ireland 6154 0x180A Spanish – Panama 7169 0x1C01 Arabic – Tunisia 7177 0x1C09 English – South Africa 7178 0x1C0A Spanish – Dominican Republic 8193 0x2001 Arabic – Oman 8201 0x2009 English – Jamaica 8202 0x200A Spanish – Venezuela 9217 0x2401 Arabic – Yemen 9226 0x240A Spanish – Colombia 10241 0x2801 Arabic – Syria 10249 0x2809 English – Belize 10250 0x280A Spanish – Peru 11265 0x2C01 Arabic – Jordan 11273 0x2C09 English – Trinidad 11274 0x2C0A Spanish – Argentina 12289 0x3001 Arabic – Lebanon 12298 0x300A Spanish – Ecuador 13313 0x3401 Arabic – Kuwait 13322 0x340A Spanish – Chile 14337 0x3801 Arabic – U.A.E. 14346 0x380A Spanish – Uruguay 15361 0x3C01 Arabic – Bahrain 15370 0x3C0A Spanish – Paraguay 16385 0x4001 Arabic – Qatar 16394 0x400A Spanish – Bolivia 17418 0x440A Spanish – El Salvador 18442 0x480A Spanish – Honduras 19466 0x4C0A Spanish – Nicaragua 20490 0x500A Spanish – Puerto Rico OSProductSuite Data type: uint32 Access type: Только для чтения Installed and licensed system product additions to the operating system. For example, the value of 146 (0x92) for OSProductSuite indicates Enterprise, Terminal Server, and Data Center (bits one, four, and seven set). The following table lists possible values. Value Meaning 1 0x1 Microsoft Small Business Server was once installed, but may have been upgraded to another version of Windows. Windows Server 2003, Windows XP, and Windows 2000: Small Business 2 0x2 Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed. Windows Server 2003, Windows XP, and Windows 2000: Enterprise 4 0x4 Windows BackOffice components are installed. Windows Server 2003, Windows XP, and Windows 2000: BackOffice 8 0x8 Communication Server is installed. Windows Server 2003, Windows XP, and Windows 2000: Communication Server 16 0x10 Terminal Services is installed. Windows Server 2003, Windows XP, and Windows 2000: Terminal Server 32 0x20 Microsoft Small Business Server is installed with the restrictive client license. Windows Server 2003, Windows XP, and Windows 2000: Small Business (Restricted) 64 0x40 Windows XP Embedded is installed. Windows Server 2003 and Windows XP: Embedded NT 128 0x80 Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition, or Windows 2000 Datacenter Server is installed. Windows Server 2003, Windows XP, and Windows 2000: Data Center 256 0x100 Terminal Services is installed, but only one interactive session is supported. Windows Server 2003, Windows XP, and Windows 2000: This value is not available. 512 0x200 Windows XP Home Edition is installed. Windows Server 2003, Windows XP, and Windows 2000: This value is not available. 1024 0x400 Windows Server 2003, Web Edition is installed. Windows Server 2003, Windows XP, and Windows 2000: This value is not available. 8192 0x2000 Windows Storage Server 2003 R2 is installed. Windows Server 2003, Windows XP, and Windows 2000: This value is not available. 16384 0x4000 Windows Server 2003, Compute Cluster Edition is installed. Windows Server 2003, Windows XP, and Windows 2000: This value is not available. OSType Data type: uint16 Access type: Только для чтения Type of operating system. The following list identifies the possible values. Values Meaning 0 0x0 Unknown 1 0x1 Other 2 0x2 MACROS 3 0x3 ATTUNIX 4 0x4 DGUX 5 0x5 DECNT 6 0x6 Digital UNIX 7 0x7 OpenVMS 8 0x8 HPUX 9 0x9 AIX 10 0xA MVS 11 0xB OS400 12 0xC OS/2 13 0xD JavaVM 14 0xE MSDOS 15 0xF WIN3x 16 0x10 WIN95 17 0x11 WIN98 18 0x12 WINNT 19 0x13 WINCE 20 0x14 NCR3000 21 0x15 NetWare 22 0x16 OSF 23 0x17 DC/OS 24 0x18 Reliant UNIX 25 0x19 SCO UnixWare 26 0x1A SCO OpenServer 27 0x1B Sequent 28 0x1C IRIX 29 0x1D Solaris 30 0x1E SunOS 31 0x1F U6000 32 0x20 ASERIES 33 0x21 TandemNSK 34 0x22 TandemNT 35 0x23 BS2000 36 0x24 LINUX 37 0x25 Lynx 38 0x26 XENIX 39 0x27 VM/ESA 40 0x28 Interactive UNIX 41 0x29 BSDUNIX 42 0x2A FreeBSD 43 0x2B NetBSD 44 0x2C GNU Hurd 45 0x2D OS9 46 0x2E MACH Kernel 47 0x2F Inferno 48 0x30 QNX 49 0x31 EPOC 50 0x32 IxWorks 51 0x33 VxWorks 52 0x34 MiNT 53 0x35 BeOS 54 0x36 HP MPE 55 0x37 NextStep 56 0x38 PalmPilot 57 0x39 Rhapsody OtherTypeDescription Data type: string Access type: Только для чтения Additional description for the current operating system version. Windows Server 2003 R2: Contains the string "R2". Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: OtherTypeDescription is null. PAEEnabled Data type: Boolean Access type: Только для чтения If True, the physical address extensions (PAE) are enabled by the operating system running on Intel processors. PAE allows applications to address more than 4 GB of physical memory. When PAE is enabled, the operating system uses three-level linear address translation rather than two-level. Providing more physical memory to an application reduces the need to swap memory to the page file and increases performance. To enable, PAE, use the "/PAE" switch in the Boot.ini file. For more information about the Physical Address Extension feature, see http://go.microsoft.com/fwlink?LinkID=45912. Windows XP, Windows 2000, and Windows NT 4.0 SP4 and later: The PAEEnabled property is not available. PlusProductID Data type: string Access type: Только для чтения Identification number for the Windows Plus! operating system enhancement software—if installed. PlusVersionNumber Data type: string Access type: Только для чтения Version number of the Windows Plus! operating system enhancement software—if installed. Primary Data type: boolean Access type: Только для чтения Specifies whether this is the primary operating system. ProductType Data type: uint32 Access type: Только для чтения Additional system information. Value Meaning 1 Work Station 2 Domain Controller 3 Server Windows 2000 and Windows NT 4.0 SP4 and later: This property is not available. QuantumLength Data type: uint8 Access type: Read/write Number of clock ticks per quantum. A quantum is a unit of execution time that the scheduler is allowed to give to an application before switching to other applications. When a thread runs one quantum, the kernel preempts it and moves it to the end of a queue for applications with equal priorities. The actual length, of a thread quantum, varies across different Windows platforms—Windows NT and Windows 2000 only. Value Meaning 1 Unknown 2 One Tick 3 Two Ticks QuantumType Data type: uint8 Access type: Read/write Length type of quantums. Windows NT Workstation and Windows 2000 defaults to variable-length quantums where the foreground application has a longer quantum than the background applications. Windows NT Server defaults to fixed-length quantums. A quantum is a unit of execution time that the scheduler is allowed to give to an application before switching to another application. When a thread runs one quantum, the kernel preempts it and moves it to the end of a queue for applications with equal priorities. The actual length of a thread quantum varies across different Windows platforms. For Windows NT and Windows 2000 only. Value Meaning 1 Unknown 2 Fixed 3 Variable RegisteredUser Access type: Только для чтения Name of the registered user of the operating system. Example: "Ben Smith" SerialNumber Access type: Только для чтения Operating system product serial identification number. Example: "10497-OEM-0031416-71674" ServicePackMajorVersion Data type: uint16 Access type: Только для чтения Major version number of the service pack installed on the computer system. If no service pack has been installed, the value is 0 (zero). Windows NT 4.0 and Windows Me/98/95: This property is present but the value is NULL. ServicePackMinorVersion Data type: uint16 Access type: Только для чтения Minor version number of the service pack installed on the computer system. If no service pack has been installed, the value is 0 (zero). Windows NT 4.0 and Windows Me/98/95: This property is present but the value is NULL. SizeStoredInPagingFiles Access type: Только для чтения Total number of kilobytes that can be stored in the operating system paging files—0 (zero) indicates that there are no paging files. Be aware that this number does not represent the actual physical size of the paging file on disk. For more information about using uint64 values in scripts, see Scripting in WMI. Status Access type: Только для чтения Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive may function properly, but predicts a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The Service status applies to administrative work, such as mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, but the managed element is neither "OK" nor in one of the other states. The values are: "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service" SuiteMask Data type: uint32 Access type: Только для чтения Bit flags that identify the product suites available on the system. Windows 2000 и Windows NT 4.0 SP4 and later: This property is not available. For example, to specify both Personal and BackOffice, set SuiteMask to 4 | 512 or 516. The following table lists possible values. Value Meaning 1 Small Business 2 Enterprise 4 BackOffice 8 Communications 16 Terminal 32 Small Business Restricted 64 Embedded NT 128 Data Center 256 Single User 512 Personal 1024 Blade SystemDevice Access type: Только для чтения Physical disk partition on which the operating system is installed. SystemDirectory Access type: Только для чтения System directory of the operating system. Example: "C:\WINDOWS\SYSTEM32" SystemDrive Access type: Только для чтения Letter of the disk drive on which the operating system resides. Example: "C:" Windows 2000 and Windows NT 4.0 SP4 and later: This property is not available. TotalSwapSpaceSize Access type: Только для чтения Total swap space in kilobytes. This value may be NULL (unspecified) if the swap space is not distinguished from page files. However, some operating systems distinguish these concepts. For example, in UNIX, whole processes can be swapped out when the free page list falls and remains below a specified amount. For more information about using uint64 values in scripts, see Scripting in WMI. TotalVirtualMemorySize Access type: Только для чтения Number, in kilobytes, of virtual memory. For example, this may be calculated by adding the amount of total RAM to the amount of paging space, that is, adding the amount of memory in or aggregated by the computer system to the property, SizeStoredInPagingFiles. For more information about using uint64 values in scripts, see Scripting in WMI. TotalVisibleMemorySize Access type: Только для чтения Total amount of physical memory available to the operating system. This value does not necessarily indicate the true amount of physical memory, but what is reported to the operating system as available to it. For more information about using uint64 values in scripts, see Scripting in WMI. Version Access type: Только для чтения Version number of the operating system. Example: "4.0" WindowsDirectory Data type: string Access type: Только для чтения Windows directory of the operating system. Example: "C:\WINDOWS"

Примечания

Класс Win32_OperatingSystem наследует от CIM_OperatingSystem.

Пример

Пример с применением сценария VBS

On Error Resume Next
' Connect to WMI and obtain instances of Win32_OperatingSystem
For Each objOS in GetObject( _
    "winmgmts:").InstancesOf ("Win32_OperatingSystem")

WScript.Echo "Имя = " & objOS.Caption &VBCR _
    & "Версия = " & objOS.Version &VBCR _
    & "Пользователь = " & objOS.RegisteredUser &VBCR _
    & "Производитель = " & objOS.Manufacturer &VBCR _
    '& "OperatingSystemSKU = " & objOS.OperatingSystemSKU   ' для Vista
Next

If Err <> 0 Then
    WScript.Echo Err.Description
    Err.Clear
End If

Пример для Visual Basic 2008 можно скачать со страницы примеров.

Смотри также

Operating System Classes


Win32_OperatingSystem.Reboot

Метод Reboot (класс Win32_OperatingSystem)

Метод Reboot перезагружает систему.

uint32 Reboot();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

В успешном случае возвращается 0, в случае ошибки возвращается ненулевое значение.

Пример

Пример с применением сценария VBS

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Перезагрузка", "localhost")

Set OS = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_OperatingSystem WHERE Primary = true")

For Each System in OS
    System.Reboot()
Next

Выражение Primary = true проверяет, что ОС Windows является основной операционной системой в текущий момент.

Смотри также

Win32_OperatingSystem


Win32_OperatingSystem.Shutdown

Метод Shutdown (класс Win32_OperatingSystem)

Метод Shutdown выгружает программы и библиотеки DLL и выключает компьютер.

uint32 Shutdown();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

В успешном случае возвращается 0, в случае ошибки возвращается ненулевое значение.

Пример

Пример с применением сценария VBS

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Выключение", "localhost")

Set OS = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_OperatingSystem WHERE Primary = true")

For Each System in OS
    System.Shutdown()
Next

Выражение Primary = true проверяет, что ОС Windows является основной операционной системой в текущий момент.

Пример на C#

using System.Management;

const string Query = "SELECT * FROM Win32_OperatingSystem";

private void button1_Click(object sender, EventArgs e)
{
    ManagementScope scope = new ManagementScope();
    scope.Options.EnablePrivileges = true;
    scope.Connect();
    ObjectQuery query = new ObjectQuery(Query);
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    foreach (ManagementObject obj in searcher.Get())
    {
        obj.InvokeMethod("Shutdown", new object[] { });
    }
}

Смотри также

Win32_OperatingSystem


Win32_Process

Класс Win32_Process позволяет работать с процессами операционной системы.

class Win32_Process : CIM_Process
{
  string Caption;
  string CommandLine;
  string CreationClassName;
  datetime CreationDate;
  string CSCreationClassName;
  string CSName;
  string Description;
  string ExecutablePath;
  uint16 ExecutionState;
  string Handle;
  uint32 HandleCount;
  datetime InstallDate;
  uint64 KernelModeTime;
  uint32 MaximumWorkingSetSize;
  uint32 MinimumWorkingSetSize;
  string Name;
  string OSCreationClassName;
  string OSName;
  uint64 OtherOperationCount;
  uint64 OtherTransferCount;
  uint32 PageFaults;
  uint32 PageFileUsage;
  uint32 ParentProcessId;
  uint32 PeakPageFileUsage;
  uint64 PeakVirtualSize;
  uint32 PeakWorkingSetSize;
  uint32 Priority;
  uint64 PrivatePageCount;
  uint32 ProcessId;
  uint32 QuotaNonPagedPoolUsage;
  uint32 QuotaPagedPoolUsage;
  uint32 QuotaPeakNonPagedPoolUsage;
  uint32 QuotaPeakPagedPoolUsage;
  uint64 ReadOperationCount;
  uint64 ReadTransferCount;
  uint32 SessionId;
  string Status;
  datetime TerminationDate;
  uint32 ThreadCount;
  uint64 UserModeTime;
  uint64 VirtualSize;
  string WindowsVersion;
  uint64 WorkingSetSize;
  uint64 WriteOperationCount;
  uint64 WriteTransferCount;
};

Методы

Метод | Описание
AttachDebugger | Launches the currently registered debugger for a process
Create | Создает новый процесс
GetOwner | Retrieves the user name and domain name under which the process is running.
GetOwnerSid | Retrieves the security identifier (SID) for the owner of a process.
SetPriority | Changes the execution priority of a process.
Terminate | Прекращает выполнение процесса и всех его потоков.

Свойства

Caption
Только для чтения. Короткое (в одну строку) описание объекта
CommandLine
Access type: Read-only Command line used to start a specific process, if applicable. This property is new for Windows XP. CreationClassName Data type: string Access type: Read-only Qualifiers: Key, MaxLen(256) Name of the first concrete class in the inheritance chain that is used to create an instance. You can use this property with other key properties of the class to uniquely identify all of the instances of the class and its subclasses. This property is inherited from CIM_System. CreationDate Data type: datetime Access type: Read-only Date the process begins executing. CSCreationClassName Data type: string Access type: Read-only Creation class name of the scoping computer system. CSName Data type: string Access type: Read-only Name of the scoping computer system. Description Data type: string Access type: Read-only Description of an object. ExecutablePath Data type: string Access type: Read-only Qualifiers: Privileges(SeDebugPrivilege) Path to the executable file of the process. Example: C:\WINDOWS\EXPLORER.EXE ExecutionState Data type: uint16 Access type: Read-only This property is not implemented and does not get populated for any instance of this class. This property is always NULL. Handle Data type: string Access type: Read-only Qualifiers: Key Process identifier. HandleCount Data type: uint32 Access type: Read-only Total number of open handles owned by the process. HandleCount is the sum of the handles currently open by each thread in this process. A handle is used to examine or modify the system resources. Each handle has an entry in a table that is maintained internally. Entries contain the addresses of the resources and data to identify the resource type. InstallDate Data type: datetime Access type: Read-only Date an object is installed. The object may be installed without a value being written to this property. KernelModeTime Data type: uint64 Access type: Read-only Time in kernel mode, in 100 nanosecond units. If this information is not available, use a value of 0 (zero). For more information about using uint64 values in scripts, see Scripting in WMI. MaximumWorkingSetSize Data type: uint32 Access type: Read-only Qualifiers: Privileges(SeDebugPrivilege), Units(Kilobytes) Maximum working set size of the process. The working set of a process is the set of memory pages visible to the process in physical RAM. These pages are resident, and available for an application to use without triggering a page fault. Example: 1413120 MinimumWorkingSetSize Data type: uint32 Access type: Read-only Qualifiers: Privileges(SeDebugPrivilege), Units(Kilobytes) Minimum working set size of the process. The working set of a process is the set of memory pages visible to the process in physical RAM. These pages are resident and available for an application to use without triggering a page fault. Example: 20480 Name Data type: string Access type: Read-only Label for an object. When inherited by a subclass, the property can be overridden to be a key property. OSCreationClassName Data type: string Access type: Read-only Creation class name of the scoping operating system. OSName Data type: string Access type: Read-only Name of the scoping operating system. OtherOperationCount Data type: uint64 Access type: Read-only Number of I/O operations performed that are not read or write operations. For more information about using uint64 values in scripts, see Scripting in WMI. OtherTransferCount Data type: uint64 Access type: Read-only Qualifiers: Units(Bytes) Amount of data transferred during operations that are not read or write operations. For more information about using uint64 values in scripts, see Scripting in WMI. PageFaults Data type: uint32 Access type: Read-only Number of page faults that a process generates. Example: 10 PageFileUsage Data type: uint32 Access type: Read-only Qualifiers: Units(Kilobytes) Amount of page file space that a process is using currently. This value is consistent with the VMSize value in TaskMgr.exe. Example: 102435 ParentProcessId Data type: uint32 Access type: Read-only Unique identifier of the process that creates a process. Process identifier numbers are reused, so they only identify a process for the lifetime of that process. It is possible that the process identified by ParentProcessId is terminated, so ParentProcessId may not refer to a running process. It is also possible that ParentProcessId incorrectly refers to a process that reuses a process identifier. You can use the CreationDate property to determine whether the specified parent was created after the process represented by this Win32_Process instance was created. PeakPageFileUsage Data type: uint32 Access type: Read-only Qualifiers: Units(Kilobytes) Maximum amount of page file space used during the life of a process. Example: 102367 PeakVirtualSize Data type: uint64 Access type: Read-only Qualifiers: Units(Bytes) Maximum virtual address space a process uses at any one time. Using virtual address space does not necessarily imply corresponding use of either disk or main memory pages. However, virtual space is finite, and by using too much the process might not be able to load libraries. For more information about using uint64 values in scripts, see Scripting in WMI. PeakWorkingSetSize Data type: uint32 Access type: Read-only Qualifiers: Units(Kilobytes) Peak working set size of a process. Example: 1413120 Priority Data type: uint32 Access type: Read-only Scheduling priority of a process within an operating system. The higher the value, the higher priority a process receives. Priority values can range from 0 (zero), which is the lowest priority to 31, which is highest priority. Example: 7 PrivatePageCount Data type: uint64 Access type: Read-only Current number of pages allocated that are only accessible to the process represented by this Win32_Process instance. For more information about using uint64 values in scripts, see Scripting in WMI. ProcessId Data type: uint32 Access type: Read-only Global process identifier that is used to identify a process. The value is valid from the time a process is created until it is terminated. QuotaNonPagedPoolUsage Data type: uint32 Access type: Read-only Quota amount of nonpaged pool usage for a process. Example: 15 QuotaPagedPoolUsage Data type: uint32 Access type: Read-only Quota amount of paged pool usage for a process. Example: 22 QuotaPeakNonPagedPoolUsage Data type: uint32 Access type: Read-only Peak quota amount of nonpaged pool usage for a process. Example: 31 QuotaPeakPagedPoolUsage Data type: uint32 Access type: Read-only Peak quota amount of paged pool usage for a process. Example: 31 ReadOperationCount Data type: uint64 Access type: Read-only Number of read operations performed. For more information about using uint64 values in scripts, see Scripting in WMI. ReadTransferCount Data type: uint64 Access type: Read-only Qualifiers: Units(Bytes) Amount of data read. For more information about using uint64 values in scripts, see Scripting in WMI. SessionId Data type: uint32 Access type: Read-only Unique identifier that an operating system generates when a session is created. A session spans a period of time from logon until logoff from a specific system. Status Data type: string Access type: Read-only This property is not implemented and does not get populated for any instance of this class. It is always NULL. TerminationDate Data type: datetime Access type: Read-only Process was stopped or terminated. To get the termination time, a handle to the process must be held open. Otherwise, this property returns NULL. ThreadCount Data type: uint32 Access type: Read-only Number of active threads in a process. An instruction is the basic unit of execution in a processor, and a thread is the object that executes an instruction. Each running process has at least one thread. Windows Me/98/95: This property is not available. UserModeTime Data type: uint64 Access type: Read-only Time in user mode, in 100 nanosecond units. If this information is not available, use a value of 0 (zero). For more information about using uint64 values in scripts, see Scripting in WMI. VirtualSize Data type: uint64 Access type: Read-only Qualifiers: Units(Bytes) Current size of the virtual address space that a process is using, not the physical or virtual memory actually used by the process. Using virtual address space does not necessarily imply corresponding use of either disk or main memory pages. Virtual space is finite, and by using too much, the process might not be able to load libraries. This value is consistent with what you see in Perfmon.exe. For more information about using uint64 values in scripts, see Scripting in WMI. WindowsVersion Data type: string Access type: Read-only Version of Windows in which the process is running. Example: 4.0 WorkingSetSize Data type: uint64 Access type: Read-only Amount of memory in bytes that a process needs to execute efficiently—for an operating system that uses page-based memory management. If the system does not have enough memory (less than the working set size), thrashing occurs. If the size of the working set is not known, use NULL or 0 (zero). If working set data is provided, you can monitor the information to understand the changing memory requirements of a process. For more information about using uint64 values in scripts, see Scripting in WMI. WriteOperationCount Data type: uint64 Access type: Read-only Number of write operations performed. For more information about using uint64 values in scripts, see Scripting in WMI. WriteTransferCount Data type: uint64 Access type: Read-only Qualifiers: Units(Bytes) Amount of data written. For more information about using uint64 values in scripts, see Scripting in WMI.

Примечания

Класс Win32_Process наследует от CIM_Process.

Пример

Пример с применением сценария VBS

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process")

For Each objProcess in colItems
    Wscript.Echo "Description: " & objProcess.Description
Next

The following VBScript code example shows how to obtain the owner of each process on a local computer. You can use this script to obtain data from a remote computer, for example, to determine which users have processes running terminal server, substitute the name of the remote computer for "." in the first line. You must also be an administrator on the remote machine.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & strComputer & "\root\cimv2")

Set colProcesses = objWMIService.ExecQuery( _
    "select * from win32_process" )
For Each objProcess in colProcesses

    If objProcess.GetOwner ( User, Domain ) = 0 Then
          Wscript.Echo "Process " & _
              objProcess.Caption & _
              " belongs to " & Domain & _
              "\" & User
    Else
          Wscript.Echo "Problem " & Rtn & _
              " getting the owner for process " _
              & objProcess.Caption
    End If
Next

The following VBScript code example shows how to obtain the logon session associated with a running process. A process must be running Notepad.exe before the script starts. The example locates the instances of Win32_LogonSession associated with the Win32_Process that represents Notepad.exe. Win32_SessionProcess is specified as the association class. For more information, see ASSOCIATORS OF Statement.

 On error resume next
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & "." & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery( _
    "Select * from Win32_Process " _
    & "Where Name = 'Notepad.exe'")
For Each objProcess in colProcesses
    ProcessId = objProcess.ProcessId
    Set colLogonSessions = objWMIService.ExecQuery _
       ("Associators of {Win32_Process='" _
          & ProcessId & "'} Where" _
          & " Resultclass = Win32_LogonSession" _
          & " Assocclass = Win32_SessionProcess", "WQL", 48)
             If Err <> 0 Then
                WScript.Echo "Error on associators query= " _
                   & Err.number _
                   & " " & Err.Description
                WScript.Quit
             End If
   For Each LogonSession in colLogonSessions
      Wscript.Echo " Logon id is " & LogonSession.LogonId
   Next
Next

Смотри также

Operating System Classes


Win32_Process.Create

Метод Create (класс Win32_Process)

Метод Create позволяет создать новый процесс.

uint32 Create(
  [in]                 string CommandLine,
  [in]                 string CurrentDirectory,
  [in]                 Win32_ProcessStartup ProcessStartupInformation,
  [out]                uint32 ProcessId
);

Параметры

CommandLine
Command line to execute. The system adds a null character to the command line, trimming the string if necessary, to indicate which file was actually used.
CurrentDirectory
Current drive and directory for the child process. The string requires that the current directory resolves to a known path. A user can specify an absolute path or a path relative to the current working directory. If this parameter is NULL, the new process will have the same path as the calling process. This option is provided primarily for shells that must start an application and specify the application's initial drive and working directory.
ProcessStartupInformation
The startup configuration of a Windows process. For more information, see Win32_ProcessStartup
ProcessId
Global process identifier that can be used to identify a process. The value is valid from the time the process is created until the time the process is terminated.

Возвращаемое значение

Возвращает 0 в успешном случае (был создан процесс). В случае ошибки возвращаются следующие значения

Значение | Описание
0 | Success
2 | Access Denied
3 | Unsufficient Privilege
8 | Unknown Failure
9 | Path Not Found
21 | Invalid Parameter

Пример

Пример с применением сценария VBS. Создадим процесс Notepad на локальном компьютере. Для настройки процесса используется Win32_ProcessStartup.

Const SW_NORMAL = 1
strComputer = "."
strCommand = "Notepad.exe"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & strComputer & "\root\cimv2")

' Configure the Notepad process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL

' Create Notepad process
Set objProcess = objWMIService.Get("Win32_Process")
intReturn = objProcess.Create _
    (strCommand, Null, objConfig, intProcessID)
If intReturn <> 0 Then
    Wscript.Echo "Process could not be created." & _
        vbNewLine & "Command line: " & strCommand & _
        vbNewLine & "Return value: " & intReturn
Else
    Wscript.Echo "Process created." & _
        vbNewLine & "Command line: " & strCommand & _
        vbNewLine & "Process ID: " & intProcessID
End If

Смотри также

Win32_Process


Win32_Process.Terminate

Метод Terminate (класс Win32_Process)

Метод Terminate позволяет прекратить выполнение процесса и все его потоки. Метод позволяет закрывать процессы на удаленной машине.

uint32 Terminate(
  [in]                 uint32 Reason
);

Параметры

Reason
Код выхода для процесса и его потоков.

Возвращаемое значение

Возвращает 0 в успешном случае (был процесс был завершен). В случае ошибки возвращаются следующие значения

Значение | Описание
0 | Успешное выполнение
2 | Отказано в доступе
3 | Unsufficient Privilege
8 | Unknown Failure
9 | Путь не найден
21 | Неверный параметр

Пример

Сценарий VBScript соединяется с удаленным компьютером и завершает на нем процесс Notepad.exe.

strComputer = "FullComputerName"
strDomain = "DOMAIN"
strUser = InputBox("Enter user name")
strPassword = InputBox("Enter password")
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objSWbemLocator.ConnectServer(strComputer, _
    "root\CIMV2", _
    strUser, _
    strPassword, _
    "MS_409", _
    "ntlmdomain:" + strDomain)
Set colProcessList = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_Process WHERE Name = 'notepad.exe'")
For Each objProcess in colProcessList
    objProcess.Terminate()
Next

Смотри также

Win32_Process


Win32_Product

Класс Win32_Product позволяет получить информацию об установленных программах при помощи инсталятора Windows Installer

class Win32_Product : CIM_Product
{
  uint16 AssignmentType;
  string Caption;
  string Description;
  string IdentifyingNumber;
  string InstallDate;
  datetime InstallDate2;
  string InstallLocation;
  sint16 InstallState;
  string HelpLink;
  string HelpTelephone;
  string InstallSource;
  string Language;
  string LocalPackage;
  string Name;
  string PackageCache;
  string PackageCode;
  string PackageName;
  string ProductID;
  string PackageName;
  string RegOwner;
  string RegCompany;
  string SKUNumber;
  string Transforms;
  string URLInfoAbout;
  string URLUpdateInfo;
  string Vendor;
  uint32 WordCount;
  string Version;
};

Методы

Метод | Описание
Install | Installs an associated Win32_Product instance using the installation package provided through PackageLocation and any command line options that are supplied.
Admin | Performs an administrative install of an associated Win32_Product instance using the installation package provided through PackageLocation, and any command line options that are supplied.
Advertise | Advertises an associated Win32_Product instance using the installation package provided through PackageLocation and any command line options that are supplied.
Reinstall | Reinstalls the associated instance of Win32_Product using the specified reinstallation mode.
Upgrade | Upgrades the associated Win32_Product instance using the upgrade package provided through PackageLocation and any command line options that are supplied.
Configure | Configures the associated instance of Win32_Product to the specified install state and level.
Uninstall | Uninstalls the associated instance of Win32_Product.

Свойства

AssignmentType Data type: uint16 Access type: Read-only Assignment type of the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. Possible values are Value Meaning 0 The product is assigned by user. 1 The product is assigned by computer. Caption Data type: string Access type: Read-only Short textual description for the product—a one-line string. Description Data type: string Access type: Read-only Description of the product. HelpLink Data type: string Access type: Read-only The support link for the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. HelpTelephone Data type: string Access type: Read-only The support telephone for the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. IdentifyingNumber Data type: string Access type: Read-only Product identification such as a serial number on software, or a die number on a hardware chip. InstallDate Data type: string Access type: Read-only Starting with Windows XP this property is no longer supported for Win32_Product. Instead, use the InstallDate2 property, which is in the WMI CIM_DATETIME format. Windows 2000: Date that this product is installed on the system. This property does not need a value to indicate that the object is installed. InstallDate2 Data type: datetime Access type: Read-only Date that this product was installed on the system. This property does not require a value to indicate that the object is installed. For more information about WMI dates and times, see Date and Time Format. Windows 2000: This property is not available. InstallLocation Data type: string Access type: Read-only Location of the installed product. InstallSource Data type: string Access type: Read-only The installation source directory of the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. InstallState Data type: sint16 Access type: Read-only Installed state of the product. Value Meaning -6 Bad Configuration -2 Invalid Argument -1 Unknown Package 1 Advertised 2 Absent 5 Installed Language Data type: string Access type: Read-only The language of the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. LocalPackage Data type: string Access type: Read-only The location of the locally cached package for this product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. Name Data type: string Access type: Read-only Qualifiers: Key Commonly used product name. PackageCache Data type: string Access type: Read-only Location of the locally cached package for this product. PackageCode Data type: string Access type: Read-only The identifier for the package from which this product was installed. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. PackageName Data type: string Access type: Read-only The original package name for the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. PackageName Data type: string Access type: Read-only The original package name for the product. ProductID Data type: string Access type: Read-only The product ID. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. RegCompany Data type: string Access type: Read-only The company registered to use the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. RegOwner Data type: string Access type: Read-only The owner registered to use the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. SKUNumber Data type: string Access type: Read-only Product SKU (stock-keeping unit) information. Transforms Data type: string Access type: Read-only The transforms of the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. URLInfoAbout Data type: string Access type: Read-only The URL information for the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. URLUpdateInfo Data type: string Access type: Read-only The URL update information the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available. Vendor Data type: string Access type: Read-only Name of the product supplier. Corresponds to the Vendor property in the product object in the Desktop Management Task Force (DMTF) Solution Exchange Standard. Version Data type: string Access type: Read-only Product version information. Corresponds to the Version property in the product object in the DMTF Solution Exchange Standard. WordCount Data type: uint32 Access type: Read-only Number of words in the summary information for the product. Windows Server 2003, Windows XP, and Windows 2000: This property is not available.

Примечания

Класс Win32_Product наследует от CIM_Product.

Пример

Пример с применением сценария VBS

strComputer = "."

Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=impersonate}!\\" & _
    strComputer & _
    "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_Product")

If colSoftware.Count > 0 Then

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTextFile = objFSO.CreateTextFile( _
        "c:\SoftwareList.txt", True)

    For Each objSoftware in colSoftware
        objTextFile.WriteLine objSoftware.Caption & vbtab & _
        objSoftware.Version
    Next

    objTextFile.Close

Else
    WScript.Echo "Cannot retrieve software from this computer."

End If

Пример для JS

// Получение списка установленных программ при помощи Windows Installer

var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;

var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Product", "WQL",
                                          wbemFlagReturnImmediately | wbemFlagForwardOnly);

var enumItems = new Enumerator(colItems);
for (; !enumItems.atEnd(); enumItems.moveNext())
{
    var objItem = enumItems.item();

    WScript.Echo("Caption: " + objItem.Caption);
    WScript.Echo("Description: " + objItem.Description);
    WScript.Echo("Identifying Number: " + objItem.IdentifyingNumber);
    WScript.Echo("Install State: " + objItem.InstallState);
    WScript.Echo("Name: " + objItem.Name);
    WScript.Echo("Package Cache: " + objItem.PackageCache);
    WScript.Echo("SKU Number: " + objItem.SKUNumber);
    WScript.Echo("Vendor: " + objItem.Vendor);
    WScript.Echo("Version: " + objItem.Version);
    WScript.Echo();
}

Смотри также

Operating System Classes


Win32_QuickFixEngineering

Класс Win32_QuickFixEngineering позволяет получить информацию об установленных обновлениях Windows

class Win32_QuickFixEngineering : CIM_LogicalElement
{
  string Caption;
  string CSName;
  string Description;
  string FixComments;
  string HotFixID;
  datetime InstallDate;
  string InstalledBy;
  string InstalledOn;
  string Name;
  string ServicePackInEffect;
  string Status;
};

Методы

У класса Win32_QuickFixEngineering нет методов.

Свойства

Caption
Data type: string Access type: Read-only Short textual description (one-line string) of the object.
CSName
Data type: string Access type: Read-only Qualifiers: MaxLen(256) Local name of the computer system. The value for this property comes from the CIM_ComputerSystem class.
Description
Data type: string Access type: Read-only Description of the object.
FixComments
Data type: string Access type: Read-only Additional comments that relate to the update.
HotFixID
Data type: string Access type: Read-only Qualifiers: Key, MaxLen(260) Unique identifier associated with a particular update.
InstallDate
Data type: datetime Access type: Read-only Object was installed. This property does not require a value to indicate that the object is installed.
InstalledBy
Data type: string Access type: Read-only Person who installed the update. If this value is unknown, the property is empty.
InstalledOn
Data type: string Access type: Read-only Date that the update was installed. If this value is unknown, the property is empty.
Name
Data type: string Access type: Read-only Label by which the object is known. When subclassed, the property can be overridden to be a key property.
ServicePackInEffect
Data type: string Access type: Read-only Qualifiers: Key, MaxLen(260) Service pack in effect when the update was applied. If no service pack has been applied, the property takes on the value SP0. If it cannot be determined what service pack was in effect, this property is NULL.
Status
Data type: string Access type: Read-only Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", can apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, yet the managed element is neither "OK", nor in one of the other states. The values are: "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service"

Примечания

Класс Win32_QuickFixEngineering наследует от CIM_LogicalElement.

Пример

Пример с применением сценария JS

// Список установленных обновлений (Hot Fixes)
var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;

var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_QuickFixEngineering", "WQL",
                                          wbemFlagReturnImmediately | wbemFlagForwardOnly);

var enumItems = new Enumerator(colItems);
var infoList;

for (; !enumItems.atEnd(); enumItems.moveNext())
{
    var objItem = enumItems.item();

    infoList = "Имя: " + objItem.Caption + "\r\n";
    infoList = infoList + "Описание: " + objItem.Description + "\r\n";
    infoList = infoList + "Идентификатор: " + objItem.HotFixID + "\r\n";
    WScript.Echo(infoList);
}

Пример с применением VBS

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuickFixes = objWMIService.ExecQuery _
    ("Select * from Win32_QuickFixEngineering")
For Each objQuickFix in colQuickFixes
    Wscript.Echo "Computer: " & objQuickFix.CSName
    Wscript.Echo "Description: " & objQuickFix.Description
    Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID
Next

Смотри также

Operating System Classes


Win32_Service

Класс Win32_Service позволяет управлять службами, установленными в системе, в том числе и на удаленной машине, если имеются привилегии SC_MANAGER_CONNECT.

class Win32_Service : Win32_BaseService
{
  boolean AcceptPause;
  boolean AcceptStop;
  string Caption;
  uint32 CheckPoint;
  string CreationClassName;
  string Description;
  boolean DesktopInteract;
  string DisplayName;
  string ErrorControl;
  uint32 ExitCode;
  datetime InstallDate;
  string Name;
  string PathName;
  uint32 ProcessId;
  uint32 ServiceSpecificExitCode;
  string ServiceType;
  boolean Started;
  string StartMode;
  string StartName;
  string State;
  string Status;
  string SystemCreationClassName;
  string SystemName;
  uint32 TagId;
  uint32 WaitHint;
};

Методы

Метод | Описание
StartService | Запускает службу.
StopService | Останавливает службу
PauseService | Приостанавливает службу.
ResumeService | Возобновляет приостановленную службу.
InterrogateService | Requests that a service update its state to the service manager.
UserControlService | Attempts to send a user-defined control code to a service.
Create | Creates a new service.
Change | Modifies a service.
ChangeStartMode | Modifies the start mode of a service.
Delete | Удаляет существующую службу.
GetSecurityDescriptor | Returns the security descriptor that controls access to the service. This method is available starting with Windows Vista. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This method is not available.
SetSecurityDescriptor | Writes an updated version of the security descriptor that controls access to the service. This method is available starting with Windows Vista. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This method is not available.

Свойства

AcceptPause Data type: boolean Access type: Read-only Service can be paused. AcceptStop Data type: boolean Access type: Read-only Service can be stopped. Caption Data type: string Access type: Read-only Short description of the object—a one-line string. CheckPoint Data type: uint32 Access type: Read-only Value that the service increments periodically to report its progress during a long start, stop, pause, or continue operation. For example, the service increments this value as it completes each step of its initialization when it is starting up. The user interface program that invokes the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, pause, or continue operation pending. CreationClassName Data type: string Access type: Read-only Qualifiers: MaxLen(256) Name of the first concrete class to appear in the inheritance chain used in the creation of an instance. When used with the other key properties of the class, this property allows all instances of this class and its subclasses to be uniquely identified. Description Data type: string Access type: Read-only Description of the object. DesktopInteract Data type: boolean Access type: Read-only Service can create or communicate with windows on the desktop. DisplayName Data type: string Access type: Read-only Display name of the service. This string has a maximum length of 256 characters. The name is case-preserved in the Service Control Manager. However, DisplayName comparisons are always case-insensitive. Constraint: Accepts the same value as the Name property. Example: "Atdisk" ErrorControl Data type: string Access type: Read-only Severity of the error if this service fails to start during startup. The value indicates the action taken by the startup program if failure occurs. All errors are logged by the computer system. Value Meaning "Ignore" User is not notified. "Normal" User is notified. "Severe" System is restarted with the last-known-good configuration. "Critical" System attempts to restart with a good configuration. "Unknown" Severity of the error is unknown. ExitCode Data type: uint32 Access type: Read-only Windows error code that defines errors encountered in starting or stopping the service. This property is set to ERROR_SERVICE_SPECIFIC_ERROR (1066) when the error is unique to the service represented by this class, and information about the error is available in the ServiceSpecificExitCode property. The service sets this value to NO_ERROR when running, and again upon normal termination. InstallDate Data type: datetime Access type: Read-only Date object is installed. This property does not require a value to indicate that the object is installed. Name Data type: string Access type: Read-only Qualifiers: Key Unique identifier of the service that provides an indication of the functionality that is managed. This functionality is described in the Description property of the object. PathName Data type: string Access type: Read-only Fully-qualified path to the service binary file that implements the service. Example: "\SystemRoot\System32\drivers\afd.sys" ProcessId Data type: uint32 Access type: Read-only Process identifier of the service. Example: 324 ServiceSpecificExitCode Data type: uint32 Access type: Read-only Service-specific error code for errors that occur while the service is either starting or stopping. The exit codes are defined by the service represented by this class. This value is only set when the ExitCode property value is ERROR_SERVICE_SPECIFIC_ERROR (1066). ServiceType Data type: string Access type: Read-only Type of service provided to calling processes. The values are: "Kernel Driver" "File System Driver" "Adapter" "Recognizer Driver" "Own Process" "Share Process" "Interactive Process" Started Data type: boolean Access type: Read-only Service has been started. StartMode Data type: string Access type: Read-only Start mode of the Windows base service. Value Meaning "Boot" Device driver started by the operating system loader (valid only for driver services). "System" Device driver started by the operating system initialization process. This value is valid only for driver services. "Auto" Service to be started automatically by the service control manager during system startup. "Manual" Service to be started by the Service Control Manager when a process calls the StartService method. "Disabled" Service that cannot be started. StartName Data type: string Access type: Read-only Account name under which a service runs. Depending on the service type, the account name may be in the form of DomainName\Username. The service process is logged by using one of these two forms when it runs. If the account belongs to the built-in domain, then .\Username can be specified. For kernel or system-level drivers, StartName contains the driver object name (that is, \FileSystem\Rdr or \Driver\Xns) which the I/O system uses to load the device driver. Additionally, if NULL is specified, the driver runs with a default object name created by the I/O system based on the service name. Example: "DWDOM\Admin" Windows XP: You can use UPN format (Username@DomainName) to specify the StartName. Windows 2000: To change from a specified user to the LocalSystem account, use .\LocalSystem. State Data type: string Access type: Read-only Current state of the base service. The values are: "Stopped" "Start Pending" "Stop Pending" "Running" "Continue Pending" "Pause Pending" "Paused" "Unknown" Status Data type: string Access type: Read-only Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, yet the managed element is neither "OK" nor in one of the other states. The values are: "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service" SystemCreationClassName Data type: string Access type: Read-only Type name of the system that hosts this service. SystemName Data type: string Access type: Read-only Name of the system that hosts this service. TagId Data type: uint32 Access type: Read-only Unique tag value for this service in the group. A value of 0 (zero) indicates that the service does not have a tag. A tag can be used to order service startup within a load order group by specifying a tag order vector in the registry located at: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ GroupOrderList Tags are only evaluated for Kernel Driver and File System Driver start type services that have Boot or System start modes. WaitHint Data type: uint32 Access type: Read-only Estimated time required, in milliseconds, for a pending start, stop, pause, or continue operation. After the specified time has elapsed, the service makes its next call to the SetServiceStatus method with either an incremented CheckPoint value or a change in CurrentState. If the amount of time specified by WaitHint passes, and CheckPoint has not been incremented, or CurrentState has not changed, the service control manager or service control program assumes that an error has occurred.

Примечания

Класс Win32_Service наследует от Win32_BaseService.

Пример

Пример с применением сценария VBS. Выводим список установленных служб.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Список служб", "localhost")

Set Services = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Service")

For Each Service in Services
  If Service.State = "Paused" Then
    PList = PList & Service.Name & VBlf
  End If

  If Service.State = "Running" Then
    RList = RPList & Service.Name & VBlf
  End If

  If Service.State = "Stopped" Then
    SList = SList & Service.Name & VBlf
  End If
Next

WScript.Echo "Приостановленные службы: " & PList
WScript.Echo "Запущенные службы: " & RList
WScript.Echo "Остановленные службы: " & SList

Смотри также

Operating System Classes


Win32_Service.PauseService

Метод PauseService (класс Win32_Service)

Метод PauseService приостанавливает выполняемую службу. C помощью этого метода нельзя перевести остановленную службу в состояние приостановленной.

uint32 PauseService();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

Возможные возвращаемые значения.

Возвращаемое значение | Описание
0 | Success
1 | Не поддерживается
2 | Отказано в доступе
3 | Dependent Services Running
4 | Invalid Service Control
5 | Service Cannot Accept Control
6 | Service Not Active
7 | Service Request Timeout
8 | Unknown Failure
9 | Путь не найден
10 | Service Already Running
11 | Service Database Locked
12 | Service Dependency Deleted
13 | Service Dependency Failure
14 | Service Disabled
15 | Service Logon Failure
16 | Service Marked For Deletion
17 | Service No Thread
18 | Status Circular Dependency
19 | Status Duplicate Name
20 | Status Invalid Name
21 | Status Invalid Parameter
22 | Status Invalid Service Account
23 | Status Service Exists
24 | Service Already Paused

Пример

Пример с применением сценария VBS. Остановка службы.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Приостановка служб", "localhost")
SName = InputBox("Введите имя службы", "Приостановка служб")

Set Services = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Service WHERE = ' " & SName & "'")

For Each Service in Services
    Service.PauseService()
Next

Смотри также

Win32_Service


Win32_Service.ResumeService

Метод ResumeService (класс Win32_Service)

Метод ResumeService возобновляет приостановленную службу. C помощью этого метода нельзя запустить остановленную службу.

uint32 ResumeService();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

Возможные возвращаемые значения.

Возвращаемое значение | Описание
0 | Success
1 | Не поддерживается
2 | Отказано в доступе
3 | Dependent Services Running
4 | Invalid Service Control
5 | Service Cannot Accept Control
6 | Service Not Active
7 | Service Request Timeout
8 | Unknown Failure
9 | Путь не найден
10 | Service Already Running
11 | Service Database Locked
12 | Service Dependency Deleted
13 | Service Dependency Failure
14 | Service Disabled
15 | Service Logon Failure
16 | Service Marked For Deletion
17 | Service No Thread
18 | Status Circular Dependency
19 | Status Duplicate Name
20 | Status Invalid Name
21 | Status Invalid Parameter
22 | Status Invalid Service Account
23 | Status Service Exists
24 | Service Already Paused

Пример

Пример с применением сценария VBS. Возобновление службы.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Возобновление службы", "localhost")
SName = InputBox("Введите имя службы", "Возобновление службы")

Set Services = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Service WHERE = ' " & SName & "'")

For Each Service in Services
    Service.ResumeService()
Next

Смотри также

Win32_Service


Win32_Service.Delete

Метод Delete (класс Win32_Service)

Метод Delete удаляет существующую службу.

uint32 Delete();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

Возможные возвращаемые значения.

Возвращаемое значение | Описание
0 | Success
1 | Не поддерживается
2 | Отказано в доступе
3 | Dependent Services Running
4 | Invalid Service Control
5 | Service Cannot Accept Control
6 | Service Not Active
7 | Service Request Timeout
8 | Unknown Failure
9 | Путь не найден
10 | Service Already Running
11 | Service Database Locked
12 | Service Dependency Deleted
13 | Service Dependency Failure
14 | Service Disabled
15 | Service Logon Failure
16 | Service Marked For Deletion
17 | Service No Thread
18 | Status Circular Dependency
19 | Status Duplicate Name
20 | Status Invalid Name
21 | Status Invalid Parameter
22 | Status Invalid Service Account
23 | Status Service Exists
24 | Service Already Paused

Пример

Пример с применением сценария VBS. Возобновление службы.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Удаление службы", "localhost")
SName = InputBox("Введите имя службы", "Удаление службы")

Set Services = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Service WHERE = ' " & SName & "'")

For Each Service in Services
    Service.Delete()
Next

Смотри также

Win32_Service


Win32_Service.StartService

Метод StartService (класс Win32_Service)

Метод StartService позволяет запустить службу. Метод работает только с остановленными службами (stopped). Для приостановленных служб (paused) применяется другой метод.

uint32 StartService();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

Возможные возвращаемые значения.

Возвращаемое значение | Описание
0 | Success
1 | Не поддерживается
2 | Отказано в доступе
3 | Dependent Services Running
4 | Invalid Service Control
5 | Service Cannot Accept Control
6 | Service Not Active
7 | Service Request Timeout
8 | Unknown Failure
9 | Путь не найден
10 | Service Already Running
11 | Service Database Locked
12 | Service Dependency Deleted
13 | Service Dependency Failure
14 | Service Disabled
15 | Service Logon Failure
16 | Service Marked For Deletion
17 | Service No Thread
18 | Status Circular Dependency
19 | Status Duplicate Name
20 | Status Invalid Name
21 | Status Invalid Parameter
22 | Status Invalid Service Account
23 | Status Service Exists
24 | Service Already Paused

Пример

Пример с применением сценария VBS. Запуск остановленных служб.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Запуск служб", "localhost")
SName = InputBox("Введите имя службы", "Запуск служб")

Set Services = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Service WHERE = ' " & SName & "'")

For Each Service in Services
    Service.StartService()
Next

Смотри также

Win32_Service


Win32_Service.StopService

Метод StopService (класс Win32_Service)

Метод StopService останавливает выполняемую или приостановленную службу.

uint32 StopService();

Параметры

Данный метод не имеет параметров.

Возвращаемое значение

Возможные возвращаемые значения.

Возвращаемое значение | Описание
0 | Success
1 | Не поддерживается
2 | Отказано в доступе
3 | Dependent Services Running
4 | Invalid Service Control
5 | Service Cannot Accept Control
6 | Service Not Active
7 | Service Request Timeout
8 | Unknown Failure
9 | Путь не найден
10 | Service Already Stopped
11 | Service Database Locked
12 | Service Dependency Deleted
13 | Service Dependency Failure
14 | Service Disabled
15 | Service Logon Failure
16 | Service Marked For Deletion
17 | Service No Thread
18 | Status Circular Dependency
19 | Status Duplicate Name
20 | Status Invalid Name
21 | Status Invalid Parameter
22 | Status Invalid Service Account
23 | Status Service Exists
24 | Service Already Paused

Пример

Пример с применением сценария VBS. Остановка службы.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Остановка служб", "localhost")
SName = InputBox("Введите имя службы", "Остановка служб")

Set Services = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Service WHERE = ' " & SName & "'")

For Each Service in Services
    Service.StopService()
Next

Пример от Microsoft

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\cimv2")

Set objNetDDEservice = _
    objWMIService.Get("Win32_Service.Name='NetDDE'")

WScript.Echo "NetDDE service state: " & objNetDDEService.State
WScript.Echo "Stopping NetDDE service"
Return = objNetDDEService.StopService()
WScript.Echo "Return value: " & Return  & _
    "  Service cannot be stopped because " & _
    "dependent services are running"

Set colServiceList = objWMIService.ExecQuery("Associators of " _
    & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & _
    "Role=Antecedent" )

For Each objService in colServiceList
   WScript.Echo "Dependent service: " & objService.Name & _
   "   State: " & objService.State
   WScript.Echo "Stopping dependent service " & objService.Name
   objService.StopService()
Next

Wscript.Sleep 20000
WScript.Echo "Stopping NetDDE service"
Return = objNetDDEService.StopService()
WScript.Echo "Return value: " & Return

Смотри также

Win32_Service


Win32_Share

Класс Win32_Share осуществляет управление всеми общими ресурсами системы: каталоги, устройства, принтеры, съемные носители и др.

class Win32_Share : CIM_LogicalElement
{
  uint32 AccessMask;
  boolean AllowMaximum;
  string Caption;
  string Description;
  datetime InstallDate;
  uint32 MaximumAllowed;
  string Name;
  string Path;
  string Status;
  uint32 Type;
};

Методы

Метод | Описание
Create | Метод, который позволяет объявлять ресурс в качестве ресурса общего доступа.
Delete | Метод, который удаляет общий ресурс из списка общих ресурсов.
GetAccessMask | Returns the access rights to the share held by the user or group on whose behalf the instance is returned. You should use this method in place of the AccessMask property, which is always NULL. Windows NT 4.0 and Windows Me/98/95: This method is unavailable. Use the AccessMask property instead.
SetShareInfo | Метод, который that sets the parameters of a shared resource.

Свойства

AccessMask
Data type: uint32 Access type: Read-only This property is obsolete and is no longer used. Use the Win32_Share.GetAccessMask method instead. The value of the AccessMask property is set to null by WMI. For more information about setting access when a share is created, see the Create method. Windows 2000 and Windows NT 4.0: Bit array that represents the access rights that are required to access or perform specific operations on the file or directory. For bit values, see File and Directory Access Rights Constants. Windows Me/98/95 on Windows 98/95 FAT volumes, AccessMask: On Windows 98/95 FAT volumes, AccessMask is null. AllowMaximum Data type: boolean Access type: Read-only Number of concurrent users for this resource has been limited. If true, the value in the MaximumAllowed property is ignored.
Caption
Только для чтения. Короткое описание (одну строчку) объекта
Description
Только для чтения. Описание объекта
InstallDate Data type: datetime Access type: Read-only Object was installed. This property does not need a value to indicate that the object is installed. MaximumAllowed Data type: uint32 Access type: Read-only Limit on the maximum number of users allowed to use this resource concurrently. The value is only valid if the AllowMaximum property is set to FALSE. Name Data type: string Access type: Read-only Qualifiers: Key Alias given to a path set up as a share on a computer system running Windows. Example: "public" Path Data type: string Access type: Read-only Local path of the Windows share. Example: "C:\Program Files" Status Data type: string Access type: Read-only Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, yet the managed element is neither "OK" nor in one of the other states. The values are: "OK" "Error" "Degraded" "Unknown" "Pred Fail" "Starting" "Stopping" "Service" "Stressed" "Nonrecover" "NoContact" "LostComm" Type Data type: uint32 Access type: Read-only Type of resource being shared. Types include: disk drives, print queues, interprocess communications (IPC), and general devices. Value Meaning 0 0x0 Disk Drive 1 0x1 Print Queue 2 0x2 Device 3 0x3 IPC 2147483648 0x80000000 Disk Drive Admin 2147483649 0x80000001 Print Queue Admin 2147483650 0x80000002 Device Admin 2147483651 0x80000003 IPC Admin

Примечания

Класс Win32_Share наследует от CIM_LogicalElement.

Пример

Пример с применением сценария VBS

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Share")

For Each objItem in colItems
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Caption: " & objItem.Caption & "=" & objItem.Path
Next

Смотри также

Operating System Classes


Win32_Share.Create

Метод Create (класс Win32_Share)

Метод Create позволяет объявлять ресурс в качестве ресурса общего доступа.

uint32 Create(
  [in]                 string Path,
  [in]                 string Name,
  [in]                 uint32 Type,
  [in]                 uint32 MaximumAllowed,
  [in]                 string Description,
  [in]                 string Password,
  [in]                 Win32_SecurityDescriptor Access
);

Параметры

Path
Локальный путь общего ресурса, например, "C:\Program Files"
Name
Передает псевдоним для общего ресурса, например, "public"
Type
Тип ресурса. Может принимать одно из следующих значений: Value Meaning 0 0x0 Disk Drive 1 0x1 Print Queue 2 0x2 Device 3 0x3 IPC 2147483648 0x80000000 Disk Drive Admin 2147483649 0x80000001 Print Queue Admin 2147483650 0x80000002 Device Admin 2147483651 0x80000003 IPC Admin
MaximumAllowed Limit on the maximum number of users allowed to concurrently use this resource. Example: 10. This parameter is optional. Description Optional comment to describe the resource being shared. This parameter is optional. Password Password (when the server is running with share-level security) for the shared resource. If the server is running with user-level security, this parameter is ignored. This parameter is optional. Access Security descriptor for user level permissions. A security descriptor contains information about the permissions, owner, and access capabilities of the resource. If this parameter is not supplied or is NULL, then Everyone has read access to the share. For more information, see Win32_SecurityDescriptor and Changing Access Security on Securable Objects.

Возвращаемое значение

Returns one of the values listed in the following table, or any other value to indicate an error.

Return code Description 0 Success 2 Access Denied 8 Unknown Failure 9 Invalid Name 10 Invalid Level 21 Invalid Parameter 22 Duplicate Share 23 Redirected Path 24 Unknown Device or Directory 25 Net Name Not Found

Пример

Пример с применением сценария VBS. Объявляем ресурс в качестве ресурса общего доступа.

Смотри также

Win32_Share


Win32_Share.Delete

Метод Delete (класс Win32_Share)

Метод Delete позволяет удалять ресурсы общего доступа, имеющиеся на управляемом объекте.

uint32 Delete();

Параметры

Метод не имеет параметров

Возвращаемое значение

Возвращает одно из значений из списка или другое значение, сигнализирующее об ошибке.

Возвращаемое значение | Описание
0 | Success
2 | Access Denied
8 | Unknown Failure
9 | Invalid Name
10 | Invalid Level
21 | Invalid Parameter
22 | Duplicate Share
23 | Redirected Path
24 | Unknown Device or Directory
25 | Net Name Not Found

Пример

Пример с применением сценария VBS. Удаляем общий ресурс.

On Error Resume Next

ComputerName = InputBox("Введите имя компьютера", "Удаление общего ресурса", "localhost")
SName = InputBox("Введите имя общего ресурса", "Удаление общего ресурса")

Set Shares = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Share WHERE = ' " & SName & "'")

For Each Share in Shares
    Share.Delete()
Next

Смотри также

Win32_Share


Win32_UserAccount

Класс Win32_UserAccount позволяет получить информацию об учетных записях пользователей

class Win32_UserAccount : Win32_Account
{
  uint32   AccountType;
  string   Caption;
  string   Description;
  boolean  Disabled;
  string   Domain;
  string   FullName;
  datetime InstallDate;
  boolean  LocalAccount;
  boolean  Lockout;
  string   Name;
  boolean  PasswordChangeable;
  boolean  PasswordExpires;
  boolean  PasswordRequired;
  string   SID;
  uint8    SIDType;
  string   Status;
};

Примеры

Сценарий VBS для получения даты и времени последнего входа локальных пользователей

Option Explicit
Dim objWMIService, colItems, WshNetwork, strComputer
Dim objUser, objItem, dtmLastLogin, strLogonInfo
Set WshNetwork = CreateObject("Wscript.Network")
strComputer = WshNetwork.ComputerName

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * from Win32_UserAccount Where Domain = '" & strComputer & "'")

For Each objItem in colItems
  dtmLastLogin = ""
  On Error Resume Next
  Set objUser = GetObject("WinNT://" & strComputer _
      & "/" & objItem.Name & ",user")
  dtmLastLogin = objUser.lastLogin
  On Error Goto 0

  strLogonInfo = strLogonInfo & vbCrLf & objItem.Name & ": " & dtmLastLogin
Next
MsgBox strLogonInfo, vbOKOnly + vbInformation, "Информация о последнем входе в систему"