Ayush
Ayush

Reputation: 42450

How can i scale this to remote machines (fetching windows services)?

I have the following code that fetches all the Windows Services running on a certain machine. If the machine is the one I am running, it works fine, but if its a remote machine, I get a 'Access Denied' exception because I am not passing in the username/password.

My question is, how/where can I pass in the username/password?

static void Main(string[] args)
        {
            bool filter;
            string machineName = "mymachine";
            string objPath = String.Format("\\\\{0}\\root\\cimv2:Win32_Service",machineName);

            ManagementClass servicesMC = new ManagementClass(new ManagementPath(objPath));
            Dictionary<string, string> ServicesDict = new Dictionary<string, string>();
            List<string> Aggregate = new List<string>();

            foreach (ManagementObject service in servicesMC.GetInstances())
            {
                //Console.WriteLine(service.GetPropertyValue("Name"));
            }

Upvotes: 0

Views: 258

Answers (1)

Aamir
Aamir

Reputation: 15566

I haven't run this because I am not on a network right now but this should work:

ConnectionOptions theConnection = new ConnectionOptions();

theConnection.Username = "username";
theConnection.Password = "password";

ManagementScope scope = new ManagementScope(objPath, theConnection);
ManagementClass servicesMC = new ManagementClass(scope, new ManagementPath("Win32_Service"), new ObjectGetOptions());

Upvotes: 1

Related Questions