Home
Manage Your Code
Snippet: Remote WMI Connection (C#)
Title: Remote WMI Connection Language: C#
Description: Method to connect to a remote computer. Returns the WMI Connection scope, usable to query from. Views: 181
Author: Chad Devine Date Added: 1/25/2008
Copy Code  
1using System.Management;
2
3/// <summary>

4/// Creates a WMI connection to a computer via a trusted connection.

5/// </summary>

6/// <param name="Computer">The computer.</param>

7/// <returns></returns>

8public ManagementScope ConnectTo(string Computer)
9{
10    //If computer info is empty, default to local computer.

11    if (String.Compare(Computer.Trim(), "") == 0)
12        Computer = ".";
13
14    ConnectionOptions WMIConn = new ConnectionOptions();
15    //Impersonation does not work locally.

16    if (Computer != ".")
17    {
18        WMIConn.Impersonation = ImpersonationLevel.Impersonate;
19        WMIConn.Authentication = AuthenticationLevel.PacketPrivacy;
20        WMIConn.Authority = "ntlmdomain:YourDomain";
21    }
22
23    scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2", WMIConn);
24    scope.Options.Impersonation = ImpersonationLevel.Impersonate;
25    Console.WriteLine("Connection Success!");
26    return scope;
27}
Usage
In a trusted domain.
Notes
You must add the System.Management reference.