### Install WmiLight via NuGet Source: https://context7.com/martinkuschnik/wmilight/llms.txt Install WmiLight using the Package Manager Console or the .NET CLI. ```bash # Install via Package Manager Console Install-Package WmiLight ``` ```bash # Or via .NET CLI dotnet add package WmiLight ``` -------------------------------- ### Execute Static WMI Method to Create Process Source: https://context7.com/martinkuschnik/wmilight/llms.txt Shows how to call static WMI methods, specifically the `Create` method of the `Win32_Process` class, to start a new process. It involves getting the method definition, creating input parameters, and executing the method. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Get the Create method from Win32_Process class using (WmiMethod createMethod = connection.GetMethod("Win32_Process", "Create")) { // Create input parameters using (WmiMethodParameters methodParams = createMethod.CreateInParameters()) { // Set the command line to execute methodParams.SetPropertyValue("CommandLine", "notepad.exe"); // Execute the method uint returnValue = connection.ExecuteMethod( createMethod, methodParams, out WmiMethodParameters outParams ); if (returnValue == 0) { uint processId = outParams.GetPropertyValue("ProcessId"); Console.WriteLine($"Process created successfully with PID: {processId}"); } else { Console.WriteLine($"Failed to create process. Return code: {returnValue}"); // Return codes: 0=Success, 2=Access Denied, 3=Insufficient Privilege, // 8=Unknown Failure, 9=Path Not Found, 21=Invalid Parameter } outParams?.Dispose(); } } } ``` -------------------------------- ### Subscribe to Process Start Events (EventSubscription) Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Get notified when a process starts using WmiEventSubscription. The query specifies a 2-second interval for event detection. Ensure the WmiConnection and WmiEventSubscription are disposed. ```C# var opt = new WmiConnectionOptions() { EnablePackageEncryption = true }; using (WmiConnection connection = new WmiConnection(@"\\MACHINENAME\root\cimv2", opt)) { using (WmiEventSubscription sub = connection.CreateEventSubscription( "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'", x => Console.WriteLine("Process '{0}' started", x.GetPropertyValue("TargetInstance").GetPropertyValue("Name")))) { // ToDo: wait or do some other stuff } } ``` -------------------------------- ### Subscribe to Process Start Events (EventWatcher) Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Alternative method to get notified when a process starts using WmiEventWatcher. This approach uses an event handler for 'EventArrived'. Remember to start and stop the watcher and detach the event handler. ```C# var opt = new WmiConnectionOptions() { EnablePackageEncryption = true }; using (WmiConnection connection = new WmiConnection(@"\\MACHINENAME\root\cimv2", opt)) { using (WmiEventWatcher eventWatcher = connection.CreateEventWatcher("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'")) { eventWatcher.EventArrived += EventWatcher_EventArrived; eventWatcher.Start(); // ToDo: wait or do some other stuff eventWatcher.Stop(); eventWatcher.EventArrived -= EventWatcher_EventArrived; } } ``` -------------------------------- ### Call Non-Static WMI Method (Win32_Process Terminate) Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Shows how to call a non-static WMI method to terminate a specific process. This example iterates through processes to find 'cmd.exe' and then calls its 'Terminate' method. Ensure the method call result is checked. ```C# using (WmiConnection connection = new WmiConnection()) { foreach (WmiObject process in connection.CreateQuery("SELECT * FROM Win32_Process")) { if (process.GetPropertyValue("Name") == "cmd.exe") { using (WmiMethod terminateMethod = process.GetMethod("Terminate")) using (WmiMethodParameters parameters = terminateMethod.CreateInParameters()) { parameters.SetPropertyValue("Reason", 20); uint result = process.ExecuteMethod(terminateMethod, parameters, out WmiMethodParameters terminateOutParameters2); if (result != 0) throw new Exception($"Win32_Process::Terminate(...) failed with {result}"); } } } } ``` -------------------------------- ### Execute WQL Queries with CreateQuery Source: https://context7.com/martinkuschnik/wmilight/llms.txt Demonstrates retrieving WMI objects using WQL queries and accessing property values with GetPropertyValue. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Query all services that are currently running var query = connection.CreateQuery( "SELECT * FROM Win32_Service WHERE State = 'Running'" ); foreach (WmiObject service in query) { string name = service.GetPropertyValue("Name"); string displayName = service.GetPropertyValue("DisplayName"); string startMode = service.GetPropertyValue("StartMode"); uint processId = service.GetPropertyValue("ProcessId"); Console.WriteLine($"Service: {displayName}"); Console.WriteLine($" Name: {name}"); Console.WriteLine($" Start Mode: {startMode}"); Console.WriteLine($" PID: {processId}"); Console.WriteLine(); } // Query with conditions - find disks with less than 10GB free space foreach (WmiObject disk in connection.CreateQuery( "SELECT * FROM Win32_LogicalDisk WHERE FreeSpace < 10737418240")) { string deviceId = disk.GetPropertyValue("DeviceID"); ulong freeSpace = disk.GetPropertyValue("FreeSpace"); Console.WriteLine($"Low space warning: {deviceId} has {freeSpace / 1024 / 1024} MB free"); } } ``` -------------------------------- ### Call Static WMI Method (Win32_Process Create) Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Demonstrates calling a static WMI method to create a new process. Ensure proper disposal of WmiConnection, WmiMethod, and WmiMethodParameters. Check the return code for success. ```C# using (WmiConnection connection = new WmiConnection()) using (WmiMethod createMethod = connection.GetMethod("Win32_Process", "Create")) using (WmiMethodParameters methodParams = createMethod.CreateInParameters()) { methodParams.SetPropertyValue("CommandLine", "cmd.exe"); uint result = connection.ExecuteMethod(createMethod, methodParams, out WmiMethodParameters outParams); if (result != 0) throw new Exception($"Win32_Process::Create(...) failed with {result}"); uint processId = outParams.GetPropertyValue("ProcessId"); // ... } ``` -------------------------------- ### Create a Local WMI Connection Source: https://context7.com/martinkuschnik/wmilight/llms.txt Establish a local WMI connection to the default namespace (`\.\root\cimv2`). The connection automatically opens when a query is executed. Ensure the connection is disposed after use. ```csharp using WmiLight; // Create a local WMI connection using (WmiConnection connection = new WmiConnection()) { // Connection is ready to use // The connection automatically opens when you execute a query Console.WriteLine($"Connected: {connection.IsConnected}"); // Execute a simple query to list all running processes foreach (WmiObject process in connection.CreateQuery("SELECT * FROM Win32_Process")) { string name = process.GetPropertyValue("Name"); uint processId = process.GetPropertyValue("ProcessId"); Console.WriteLine($"Process: {name} (PID: {processId})"); } } // Connection is automatically disposed ``` -------------------------------- ### Query Running Processes Locally Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Use this to retrieve all currently running processes on the local machine. Ensure WmiConnection is properly disposed. ```C# using (WmiConnection con = new WmiConnection()) { foreach (WmiObject process in con.CreateQuery("SELECT * FROM Win32_Process")) { Console.WriteLine(process["Name"]); } } ``` -------------------------------- ### Access WmiObject Properties Source: https://context7.com/martinkuschnik/wmilight/llms.txt Illustrates accessing WMI instance properties using indexer syntax, type-safe methods, and retrieving system properties or all property names. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { foreach (WmiObject os in connection.CreateQuery("SELECT * FROM Win32_OperatingSystem")) { // Access properties using indexer (returns object) object caption = os["Caption"]; object version = os["Version"]; // Access properties with type-safe method string osName = os.GetPropertyValue("Caption"); string osVersion = os.GetPropertyValue("Version"); string architecture = os.GetPropertyValue("OSArchitecture"); ulong totalMemory = os.GetPropertyValue("TotalVisibleMemorySize"); ulong freeMemory = os.GetPropertyValue("FreePhysicalMemory"); Console.WriteLine($"Operating System: {osName}"); Console.WriteLine($"Version: {osVersion}"); Console.WriteLine($"Architecture: {architecture}"); Console.WriteLine($"Total Memory: {totalMemory / 1024} MB"); Console.WriteLine($"Free Memory: {freeMemory / 1024} MB"); // Access system properties Console.WriteLine($"Class: {os.Class}"); Console.WriteLine($"Namespace: {os.Namespace}"); Console.WriteLine($"Path: {os.Path}"); Console.WriteLine($"Server: {os.Server}"); // Get all property names Console.WriteLine("\nAll Properties:"); foreach (string propName in os.GetPropertyNames()) { object value = os[propName]; Console.WriteLine($" {propName}: {value}"); } } } ``` -------------------------------- ### Query Remote Machine Partitions with Credentials Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Query partitions on a remote machine using specified credentials. UPN format is recommended for usernames. Ensure EnablePackageEncryption is set for secure communication. ```C# var opt = new WmiConnectionOptions() { EnablePackageEncryption = true }; var cred = new NetworkCredential("USER@DOMAIN", "PASSWORD"); using (WmiConnection con = new WmiConnection(@"\\MACHINENAME\root\cimv2", cred, opt)) { foreach (WmiObject partition in con.CreateQuery("SELECT * FROM Win32_DiskPartition")) { Console.WriteLine(partition["Name"]); } } ``` -------------------------------- ### Native AOT Deployment Configuration Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Configure your project for Native AOT deployment and static linking of WmiLight. Add the specified properties to your project file. ```xml true true ``` -------------------------------- ### Native AOT Project Configuration Source: https://context7.com/martinkuschnik/wmilight/llms.txt Configures a .NET project file for Native AOT compilation, enabling static linking of WmiLight for a single executable. ```xml Exe net8.0 true true ``` -------------------------------- ### Execute Instance Method to Terminate Process Source: https://context7.com/martinkuschnik/wmilight/llms.txt Illustrates how to call non-static WMI methods on specific object instances, using the `Terminate` method of a `Win32_Process` instance to stop a running process. It includes setting parameters like the termination reason. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Find all notepad processes foreach (WmiObject process in connection.CreateQuery( "SELECT * FROM Win32_Process WHERE Name = 'notepad.exe'")) { string processName = process.GetPropertyValue("Name"); uint processId = process.GetPropertyValue("ProcessId"); Console.WriteLine($"Found process: {processName} (PID: {processId})"); // Get the Terminate method for this process instance using (WmiMethod terminateMethod = process.GetMethod("Terminate")) { // Create input parameters using (WmiMethodParameters parameters = terminateMethod.CreateInParameters()) { // Set termination reason code parameters.SetPropertyValue("Reason", (uint)0); // Execute the Terminate method on this specific process uint result = process.ExecuteMethod( terminateMethod, parameters, out WmiMethodParameters outParameters ); if (result == 0) { Console.WriteLine($"Process {processId} terminated successfully"); } else { Console.WriteLine($"Failed to terminate process. Error code: {result}"); } outParameters?.Dispose(); } } } } ``` -------------------------------- ### Subscribe to WMI Events with Callback Source: https://context7.com/martinkuschnik/wmilight/llms.txt Use CreateEventSubscription for asynchronous WMI event handling with a direct callback. Ensure the WMI query is correctly formatted and the callback handles event data. ```csharp using System; using System.Threading; using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Subscribe to process creation events // WITHIN 2 means check for events every 2 seconds using (WmiEventSubscription subscription = connection.CreateEventSubscription( "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'", eventObj => { // Get the process that was created WmiObject targetInstance = eventObj.GetPropertyValue("TargetInstance"); string processName = targetInstance.GetPropertyValue("Name"); uint processId = targetInstance.GetPropertyValue("ProcessId"); string commandLine = targetInstance.GetPropertyValue("CommandLine"); Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Process Started:"); Console.WriteLine($" Name: {processName}"); Console.WriteLine($" PID: {processId}"); Console.WriteLine($" Command: {commandLine}"); Console.WriteLine(); })) { Console.WriteLine("Listening for new processes... Press Enter to stop."); Console.WriteLine(); // Keep the subscription active Console.ReadLine(); } // Subscription is automatically cancelled when disposed } ``` -------------------------------- ### Configure Query Behavior and Timeouts Source: https://context7.com/martinkuschnik/wmilight/llms.txt Shows how to use EnumeratorBehaviorOption flags and timeout parameters to control query execution performance and property population. ```csharp using System; using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Create query with timeout and forward-only enumerator for better performance var query = connection.CreateQuery( "SELECT * FROM Win32_Process", EnumeratorBehaviorOption.ReturnImmediately | EnumeratorBehaviorOption.ForwardOnly, TimeSpan.FromSeconds(30) // 30 second timeout ); int count = 0; foreach (WmiObject process in query) { count++; Console.WriteLine($"{count}. {process.GetPropertyValue("Name")}"); } Console.WriteLine($"Total processes: {count}"); // Use EnsureLocatable to guarantee system properties are populated var locatableQuery = connection.CreateQuery( "SELECT * FROM Win32_NetworkAdapter WHERE NetEnabled = TRUE", EnumeratorBehaviorOption.ReturnImmediately | EnumeratorBehaviorOption.EnsureLocatable ); foreach (WmiObject adapter in locatableQuery) { Console.WriteLine($"Adapter: {adapter.GetPropertyValue("Name")}"); Console.WriteLine($" Path: {adapter.Path}"); Console.WriteLine($" Server: {adapter.Server}"); } } ``` -------------------------------- ### CreateEventSubscription Source: https://context7.com/martinkuschnik/wmilight/llms.txt Subscribes to WMI events asynchronously using a callback action. ```APIDOC ## CreateEventSubscription ### Description Subscribe to WMI events asynchronously using a callback action. The subscription automatically invokes your callback when events occur. ### Parameters - **query** (string) - Required - The WQL query string to filter events. - **callback** (Action) - Required - The action to execute when an event is received. ### Request Example connection.CreateEventSubscription("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'", eventObj => { ... }); ``` -------------------------------- ### Modify WMI Object Properties and Save Source: https://context7.com/martinkuschnik/wmilight/llms.txt Demonstrates how to find a WMI service, read its current properties, and modify them using `SetPropertyValue` and `Put`. Note that not all properties are writable. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Find a specific service and modify its properties foreach (WmiObject service in connection.CreateQuery( "SELECT * FROM Win32_Service WHERE Name = 'Spooler'")) { // Read current values string displayName = service.GetPropertyValue("DisplayName"); string description = service.GetPropertyValue("Description"); Console.WriteLine($"Service: {displayName}"); Console.WriteLine($"Current Description: {description}"); // Modify a property (example - not all properties are writable) // service.SetPropertyValue("Description", "Modified description"); // service.Put(); // Commit changes to WMI } // Example: Create and modify a WMI class instance // Note: This is class-specific and may require elevated privileges WmiClass environmentClass = connection.GetClass("Win32_Environment"); Console.WriteLine($"Class Name: {environmentClass.Name}"); Console.WriteLine($"Namespace: {environmentClass.Namespace}"); } ``` -------------------------------- ### Create a Remote WMI Connection with Credentials Source: https://context7.com/martinkuschnik/wmilight/llms.txt Connect to a remote machine using explicit credentials and enable package encryption for secure communication. UPN format is recommended for the username. ```csharp using System.Net; using WmiLight; // Configure connection options with encryption var options = new WmiConnectionOptions() { EnablePackageEncryption = true }; // Create credentials (UPN format recommended) var credential = new NetworkCredential("administrator@DOMAIN.COM", "SecurePassword123"); // Connect to remote machine using (WmiConnection connection = new WmiConnection(@"\\REMOTESERVER\root\cimv2", credential, options)) { // Query disk partitions on remote machine foreach (WmiObject partition in connection.CreateQuery("SELECT * FROM Win32_DiskPartition")) { string name = partition.GetPropertyValue("Name"); ulong size = partition.GetPropertyValue("Size"); Console.WriteLine($"Partition: {name}, Size: {size / 1024 / 1024} MB"); } } ``` -------------------------------- ### Native AOT Compatible WMI Query Source: https://context7.com/martinkuschnik/wmilight/llms.txt Demonstrates a WMI query that is compatible with Native AOT deployment. This code functions identically in both regular .NET and Native AOT builds. ```csharp // Native AOT compatible code using WmiLight; // This code works identically in both regular .NET and Native AOT builds using (WmiConnection connection = new WmiConnection()) { foreach (WmiObject cpu in connection.CreateQuery("SELECT * FROM Win32_Processor")) { Console.WriteLine($"CPU: {cpu.GetPropertyValue("Name")}"); Console.WriteLine($"Cores: {cpu.GetPropertyValue("NumberOfCores")}"); Console.WriteLine($"Speed: {cpu.GetPropertyValue("MaxClockSpeed")} MHz"); } } ``` -------------------------------- ### Subscribe to WMI Events with Event Handler Source: https://context7.com/martinkuschnik/wmilight/llms.txt Employ CreateEventWatcher for WMI event subscriptions using the standard .NET event pattern with explicit Start/Stop control. This is suitable for managing event listeners more granularly. ```csharp using System; using System.Threading; using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Create an event watcher for process termination events using (WmiEventWatcher eventWatcher = connection.CreateEventWatcher( "SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'")) { // Subscribe to the EventArrived event eventWatcher.EventArrived += (sender, e) => { WmiObject targetInstance = e.Event.GetPropertyValue("TargetInstance"); string processName = targetInstance.GetPropertyValue("Name"); uint processId = targetInstance.GetPropertyValue("ProcessId"); Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Process Terminated: {processName} (PID: {processId})"); }; // Start listening for events eventWatcher.Start(); Console.WriteLine("Watching for terminated processes... Press Enter to stop."); // Wait for user input Console.ReadLine(); // Stop watching eventWatcher.Stop(); Console.WriteLine("Event watcher stopped."); } } ``` -------------------------------- ### CreateEventWatcher Source: https://context7.com/martinkuschnik/wmilight/llms.txt Subscribes to WMI events using the standard .NET event pattern with explicit Start/Stop control. ```APIDOC ## CreateEventWatcher ### Description Use WmiEventWatcher for event-based subscription with explicit Start/Stop control and the standard .NET event pattern. ### Parameters - **query** (string) - Required - The WQL query string to filter events. ### Request Example using (WmiEventWatcher eventWatcher = connection.CreateEventWatcher("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'")) { eventWatcher.Start(); } ``` -------------------------------- ### Query Remote Machine Partitions with IWA Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Query partitions on a remote machine using Integrated Windows Authentication. EnablePackageEncryption is recommended for security. ```C# var opt = new WmiConnectionOptions() { EnablePackageEncryption = true }; using (WmiConnection con = new WmiConnection(@"\\MACHINENAME\root\cimv2", opt)) { foreach (WmiObject partition in con.CreateQuery("SELECT * FROM Win32_DiskPartition")) { Console.WriteLine(partition["Name"]); } } ``` -------------------------------- ### Create a Remote WMI Connection with Integrated Windows Authentication Source: https://context7.com/martinkuschnik/wmilight/llms.txt Connect to a remote machine using the current user's Windows credentials (Integrated Windows Authentication). Package encryption can be enabled for secure communication. ```csharp using WmiLight; // Configure connection options with encryption var options = new WmiConnectionOptions() { EnablePackageEncryption = true }; // Connect using Integrated Windows Authentication (no explicit credentials) using (WmiConnection connection = new WmiConnection(@"\\REMOTESERVER\root\cimv2", options)) { // Query logical disks on remote machine foreach (WmiObject disk in connection.CreateQuery("SELECT * FROM Win32_LogicalDisk")) { string deviceId = disk.GetPropertyValue("DeviceID"); ulong freeSpace = disk.GetPropertyValue("FreeSpace"); ulong totalSize = disk.GetPropertyValue("Size"); double percentFree = totalSize > 0 ? (double)freeSpace / totalSize * 100 : 0; Console.WriteLine($"Drive {deviceId}: {percentFree:F1}% free"); } } ``` -------------------------------- ### CreateQueryForRelated Source: https://context7.com/martinkuschnik/wmilight/llms.txt Queries objects associated with a specific WMI instance using the ASSOCIATORS OF WQL statement. ```APIDOC ## CreateQueryForRelated ### Description Query objects associated with a specific WMI instance using the ASSOCIATORS OF WQL statement through the CreateQueryForRelated extension method. ### Parameters - **instance** (WmiObject) - Required - The source WMI object to find associations for. - **resultClass** (string) - Optional - The specific class name to filter associated objects. ### Request Example connection.CreateQueryForRelated(disk, "Win32_DiskPartition"); ``` -------------------------------- ### Query Associated WMI Objects Source: https://context7.com/martinkuschnik/wmilight/llms.txt Utilize CreateQueryForRelated to retrieve objects associated with a specific WMI instance using ASSOCIATORS OF WQL. This method allows filtering by class name for more specific results. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Get a specific disk drive foreach (WmiObject disk in connection.CreateQuery( "SELECT * FROM Win32_DiskDrive WHERE Index = 0")) { Console.WriteLine($"Disk: {disk.GetPropertyValue("Model")}"); Console.WriteLine($"Size: {disk.GetPropertyValue("Size") / 1024 / 1024 / 1024} GB"); Console.WriteLine(); // Get all objects associated with this disk Console.WriteLine("Associated Objects:"); foreach (WmiObject associated in connection.CreateQueryForRelated(disk)) { Console.WriteLine($" Class: {associated.Class}"); } Console.WriteLine(); // Get only partitions associated with this disk Console.WriteLine("Partitions on this disk:"); foreach (WmiObject partition in connection.CreateQueryForRelated(disk, "Win32_DiskPartition")) { string name = partition.GetPropertyValue("Name"); ulong size = partition.GetPropertyValue("Size"); Console.WriteLine($" {name}: {size / 1024 / 1024} MB"); } } } ``` -------------------------------- ### Delete WMI Object Instance Source: https://context7.com/martinkuschnik/wmilight/llms.txt Deletes a WMI object instance from the repository. Ensure you have appropriate permissions before executing. The instance path is required for deletion. ```csharp using WmiLight; using (WmiConnection connection = new WmiConnection()) { // Example: Find and delete a specific environment variable // Note: This requires appropriate permissions foreach (WmiObject envVar in connection.CreateQuery( "SELECT * FROM Win32_Environment WHERE Name = 'TEMP_TEST_VAR'")) { string name = envVar.GetPropertyValue("Name"); string value = envVar.GetPropertyValue("VariableValue"); string user = envVar.GetPropertyValue("UserName"); Console.WriteLine($"Found environment variable: {name}={value} (User: {user})"); Console.WriteLine($"Path: {envVar.Path}"); // Delete the instance // connection.DeleteInstance(envVar); // Console.WriteLine("Instance deleted."); } } ``` -------------------------------- ### Prevent Trimming in Native AOT with WmiLight Source: https://github.com/martinkuschnik/wmilight/blob/master/README.md Add this to your Native AOT application's project file to ensure WmiLight code is not removed by the trimmer. This marks WmiLight as a root assembly. ```xml ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.