pub struct WMIConnection { /* private fields */ }

Implementations§

source§

impl WMIConnection

A connection to the local WMI provider, which provides querying capabilities.

Currently does not support remote providers (e.g connecting to other computers).

source

pub fn new(com_lib: COMLibrary) -> WMIResult<Self>

Creates a connection with a default CIMV2 namespace path.

source

pub fn with_namespace_path( namespace_path: &str, com_lib: COMLibrary ) -> WMIResult<Self>

Creates a connection with the given namespace path.

let wmi_con = WMIConnection::with_namespace_path("ROOT\\Microsoft\\Windows\\Storage", COMLibrary::new()?)?;
source

pub fn svc(&self) -> *mut IWbemServices

source§

impl WMIConnection

source

pub fn exec_query_native_wrapper( &self, query: impl AsRef<str> ) -> WMIResult<QueryResultEnumerator<'_>>

Execute the given query and return an iterator of WMI pointers. It’s better to use the other query methods, since this is relatively low level.

source

pub fn raw_query<T>(&self, query: impl AsRef<str>) -> WMIResult<Vec<T>>where T: DeserializeOwned,

Execute a free-text query and deserialize the results. Can be used either with a struct (like query and filtered_query), but also with a generic map.

let results: Vec<HashMap<String, Variant>> = con.raw_query("SELECT Name FROM Win32_OperatingSystem")?;
source

pub fn query<T>(&self) -> WMIResult<Vec<T>>where T: DeserializeOwned,

Query all the objects of type T.

use wmi::*;
use serde::Deserialize;

let con = WMIConnection::new(COMLibrary::new()?)?;

#[derive(Deserialize, Debug)]
struct Win32_Process {
    Name: String,
}

let procs: Vec<Win32_Process> = con.query()?;
source

pub fn filtered_query<T>( &self, filters: &HashMap<String, FilterValue> ) -> WMIResult<Vec<T>>where T: DeserializeOwned,

Query all the objects of type T, while filtering according to filters.

use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Win32_Process {
    Name: String,
}

let mut filters = HashMap::new();

filters.insert("Name".to_owned(), FilterValue::Str("cargo.exe"));

let results = con.filtered_query::<Win32_Process>(&filters).unwrap();

assert!(results.len() >= 1);
source

pub fn get<T>(&self) -> WMIResult<T>where T: DeserializeOwned,

Get a single object of type T. If none are found, an error is returned. If more than one object is found, all but the first are ignored.

use serde::Deserialize;
#[derive(Deserialize)]
struct Win32_OperatingSystem {
    Name: String,
}

let os = con.get::<Win32_OperatingSystem>()?;
source

pub fn get_raw_by_path( &self, object_path: impl AsRef<str> ) -> WMIResult<IWbemClassWrapper>

Get a WMI object by path, and return a wrapper around a WMI pointer. It’s better to use the get_by_path method, since this function is more low level.

let raw_os = con.get_raw_by_path(r#"\\.\root\cimv2:Win32_OperatingSystem=@"#)?;
assert_eq!(raw_os.class()?, "Win32_OperatingSystem");

#[derive(Deserialize)]
struct Win32_OperatingSystem {
    Name: String,
}

let os: Win32_OperatingSystem = raw_os.into_desr()?;
println!("{}", os.Name);
source

pub fn get_by_path<T>(&self, object_path: &str) -> WMIResult<T>where T: DeserializeOwned,

Get a WMI object by path, and return a deserialized object. This is useful when the type of the object at the path in known at compile time.

#[derive(Deserialize)]
struct Win32_OperatingSystem {
    Name: String,
}
let os = con.get_by_path::<Win32_OperatingSystem>(r#"\\.\root\cimv2:Win32_OperatingSystem=@"#)?;

It’s possible to have a path where the type of the WMI object is not known at compile time. Either use get_raw_by_path and the .class() to find out the real type of the object, or if the object is only of a few possible types, deserialize it to an enum:


#[derive(Deserialize, Debug, PartialEq)]
struct Win32_Group {
    __Path: String,
}

let mut filters = HashMap::new();
filters.insert("Name".into(), "Administrators".into());


let admin_group: Win32_Group = con
    .filtered_query(&filters)?
    .into_iter()
    .next()
    .unwrap();

#[derive(Deserialize, Debug, PartialEq)]
struct Win32_Account {
    __Path: String,
}

#[derive(Deserialize, Debug, PartialEq)]
struct Win32_UserAccount {
    Caption: String,
}

#[derive(Deserialize, Debug, PartialEq)]
struct Win32_SystemAccount {
    Caption: String,
}

#[derive(Deserialize, Debug, PartialEq)]
struct Win32_GroupUser{ }

// Groups contain multiple types of objects, all inheriting from `Win32_Account`.
let accounts_in_group: Vec<Win32_Account> = con.associators::<_, Win32_GroupUser>(&admin_group.__Path)?;

#[derive(Deserialize, Debug)]
enum User {
    #[serde(rename = "Win32_SystemAccount")]
    System(Win32_SystemAccount),
    #[serde(rename = "Win32_UserAccount")]
    User(Win32_UserAccount),
    #[serde(rename = "Win32_Group")]
    Group(Win32_Group),
};

for account in accounts_in_group {
    let user: User = con.get_by_path(&account.__Path)?;
    println!("{:?}", user);
}
source

pub fn associators<ResultClass, AssocClass>( &self, object_path: &str ) -> WMIResult<Vec<ResultClass>>where ResultClass: DeserializeOwned, AssocClass: DeserializeOwned,

Query all the associators of type T of the given object. The object_path argument can be provided by querying an object wih it’s __Path property. AssocClass must be have the name as the conneting association class between the original object and the results. See https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-diskdrivetodiskpartition for example.


#[derive(Deserialize, Debug)]
struct Win32_DiskDrive {
    // `__Path` is a WMI-internal property used to uniquely identify objects.
    __Path: String,
    Caption: String,
}

#[derive(Deserialize, Debug)]
struct Win32_DiskPartition {
    Caption: String,
}

// There's no need to specify any fields here, since only the name of the struct is used by `associators`.
#[derive(Deserialize, Debug)]
struct Win32_DiskDriveToDiskPartition {}

let disk = con.get::<Win32_DiskDrive>()?;
let results = con.associators::<Win32_DiskPartition, Win32_DiskDriveToDiskPartition>(&disk.__Path)?;
source§

impl WMIConnection

source

pub fn exec_query_async_native_wrapper( &self, query: impl AsRef<str> ) -> WMIResult<impl Stream<Item = WMIResult<IWbemClassWrapper>>>

Wrapper for the ExecQueryAsync method. Provides safety checks, and returns results as a Stream instead of the original Sink.

source

pub async fn async_raw_query<T>( &self, query: impl AsRef<str> ) -> WMIResult<Vec<T>>where T: DeserializeOwned,

Async version of raw_query Execute a free-text query and deserialize the results. Can be used either with a struct (like query and filtered_query), but also with a generic map.

use futures::stream::TryStreamExt;
let results: Vec<HashMap<String, Variant>> = con.async_raw_query("SELECT Name FROM Win32_OperatingSystem").await?;
source

pub async fn async_query<T>(&self) -> WMIResult<Vec<T>>where T: DeserializeOwned,

Query all the objects of type T.

use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Win32_Process {
    Name: String,
}

let procs: Vec<Win32_Process> = con.async_query().await?;
source

pub async fn async_filtered_query<T>( &self, filters: &HashMap<String, FilterValue> ) -> WMIResult<Vec<T>>where T: DeserializeOwned,

Query all the objects of type T, while filtering according to filters.

source§

impl WMIConnection

source

pub fn notification_native_wrapper( &self, query: impl AsRef<str> ) -> WMIResult<QueryResultEnumerator<'_>>

Execute the given query to receive events and return an iterator of WMI pointers. It’s better to use the other query methods, since this is relatively low level.

source

pub fn raw_notification<'a, T>( &'a self, query: impl AsRef<str> ) -> WMIResult<impl Iterator<Item = WMIResult<T>> + 'a>where T: DeserializeOwned + 'a,

Execute a free-text query and deserialize the incoming events. Returns an iterator of WMIResult<T>. Can be used either with a struct (like query and filtered_query), but also with a generic map.

let iterator = con.raw_notification::<HashMap<String, Variant>>("SELECT ProcessID, ProcessName FROM Win32_ProcessStartTrace")?;
source

pub fn notification<'a, T>( &'a self ) -> WMIResult<impl Iterator<Item = WMIResult<T>> + 'a>where T: DeserializeOwned + 'a,

Subscribe to the T event and return an iterator of WMIResult<T>.

use wmi::*;
use serde::Deserialize;

let con = WMIConnection::new(COMLibrary::new()?)?;

#[derive(Deserialize, Debug)]
struct Win32_ProcessStartTrace {
    ProcessID: u32,
    ProcessName: String,
}

let iterator = con.notification::<Win32_ProcessStartTrace>()?;
source

pub fn filtered_notification<'a, T>( &'a self, filters: &HashMap<String, FilterValue>, within: Option<Duration> ) -> WMIResult<impl Iterator<Item = WMIResult<T>> + 'a>where T: DeserializeOwned + 'a,

Subscribe to the T event, while filtering according to filters. Returns an iterator of WMIResult<T>.

use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct __InstanceCreationEvent {
    TargetInstance: Win32_Process,
}

#[derive(Deserialize, Debug)]
struct Win32_Process {
    ProcessID: u32,
}

let mut filters = HashMap::new();

filters.insert("TargetInstance".to_owned(), FilterValue::is_a::<Win32_Process>()?);

let iterator = con.filtered_notification::<__InstanceCreationEvent>(&filters, Some(Duration::from_secs(1)))?;
source

pub fn async_notification_native_wrapper( &self, query: impl AsRef<str> ) -> WMIResult<impl Stream<Item = WMIResult<IWbemClassWrapper>>>

Wrapper for the ExecNotificationQueryAsync method. Provides safety checks, and returns results as a stream instead of the original Sink.

source

pub fn async_raw_notification<T>( &self, query: impl AsRef<str> ) -> WMIResult<impl Stream<Item = WMIResult<T>>>where T: DeserializeOwned,

Async version of raw_notification Execute a free-text query and deserialize the incoming events. Returns a stream of WMIResult<T>. Can be used either with a struct (like query and filtered_query), but also with a generic map.

let mut stream = con.async_raw_notification::<HashMap<String, Variant>>("SELECT ProcessID, ProcessName FROM Win32_ProcessStartTrace")?;
source

pub fn async_notification<T>( &self ) -> WMIResult<impl Stream<Item = WMIResult<T>>>where T: DeserializeOwned,

Subscribe to the T event and return a stream of WMIResult<T>.

use futures::StreamExt;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Win32_ProcessStartTrace {
    ProcessID: u32,
    ProcessName: String,
}

let mut stream = con.async_notification::<Win32_ProcessStartTrace>()?;

let event = stream.next().await.unwrap()?;
source

pub fn async_filtered_notification<T>( &self, filters: &HashMap<String, FilterValue>, within: Option<Duration> ) -> WMIResult<impl Stream<Item = WMIResult<T>>>where T: DeserializeOwned,

Subscribe to the T event, while filtering according to filters. Returns a stream of WMIResult<T>.

use futures::StreamExt;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct __InstanceCreationEvent {
    TargetInstance: Win32_Process,
}

#[derive(Deserialize, Debug)]
struct Win32_Process {
    ProcessID: u32,
}

let mut filters = HashMap::new();

filters.insert("TargetInstance".to_owned(), FilterValue::is_a::<Win32_Process>()?);

let mut stream = con.async_filtered_notification::<__InstanceCreationEvent>(&filters, Some(Duration::from_secs(1)))?;

let event = stream.next().await.unwrap()?;

Trait Implementations§

source§

impl Clone for WMIConnection

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Drop for WMIConnection

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.