In this article, I will show you how you can stop service running on a remote computer in C# using WMI query.
First, create a console application in C# using visual studio.
Write the below code to get a service running on remote computer and stop it. To run this code you will need to add reference to System.Management dll and add a using statement.
using System.Management;
static
void
Main(
string
[] args)
{
try
{
#region Code to stop the service
//Assign the name of the service you want to stop on the remote machine
string
serviceName =
"audiosrv"
;
//Assign the user name and password of the account to ConnectionOptions object
//which have administrative privilege on the remote machine.
ConnectionOptions connectoptions =
new
ConnectionOptions();
//connectoptions.Impersonation = ImpersonationLevel.Impersonate;
connectoptions.Username =
@"Domain\UserName"
;
connectoptions.Password =
"Password"
;
//IP Address of the remote machine
string
ipAddress =
"192.168.206.53"
;
ManagementScope scope =
new
ManagementScope(
@"\\"
+ ipAddress +
@"\root\cimv2"
);
scope.Options = connectoptions;
//Define the WMI query to be executed on the remote machine
SelectQuery query =
new
SelectQuery(
"select * from Win32_Service where name = '"
+ serviceName +
"'"
);
using
(ManagementObjectSearcher searcher =
new
ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection collection=searcher.Get();
foreach
(ManagementObject service
in
collection)
{
if
(service[
"Started"
].Equals(
true
))
{
//Stop the service
service.InvokeMethod(
"StopService"
,
null
);
}
}
}
Console.ReadLine();
#endregion
}
catch
(Exception ex)
{
//Log exception in exception log.
//Logger.WriteEntry(ex.StackTrace);
Console.WriteLine(ex.StackTrace);
}
}
In this code, first we get the particualr service object using WMI query
Select * from WIN32_Service where name=servicename,
Then we invoke StopService action on the service using object.InvokeMethod to stop it if it is already running.
To access the services on the remote computer using this command, user should have administrative previlages on the remote machine. If the current user running the application has admin access on the remote machine, we can authenticate the user using Impersonation like below
connectoptions.Impersonation = ImpersonationLevel.Impersonate
or we can provide Username and password of an administrator account on the remote machine to the ConnectionOptions object like below:
connectoptions.Username =
@"Domain\UserName"
;
connectoptions.Password =
"Password"
;
Similarly to start the service, just provide StartService action in the InvokeMethod.
e.g just change the line in the above code to the following
service.InvokeMethod(
"StartService"
,
null
);
In this way, we can start and stop remote services using WMI query in C#.
Have Fun!!
Thanks much!!!!It worked first time, I have been trying to this with impersonation with no Luck
ReplyDelete