How to restart service remotely?
You could use the ServiceController class like so:
ServiceController sc = new ServiceController("ArcGIS Server", "192.168.36.22");
sc.Start();
sc.Stop();
This saves you having to write all that code to interact with WMI. Note to use the ServiceController class, you'll have to add a reference to the System.ServiceProcess assembly.
Service controller didn't work for me, so I used Cmd to do it.
Process.Start("CMD.exe", "/C sc \\\\remoteMachine stop \"serviceName\"&sc \\\\remoteMachine start \"serviceName\"");
To overcome credentials issue, I used class from this https://stackoverflow.com/a/5433640/2179222 answer.
So in the end It looked like this:
private static void RestartService(string remoteMachine, string serviceName, string userName, string password)
{
using (new NetworkConnection($"\\\\{remoteMachine}", new NetworkCredential(userName, password)))
{
Process.Start("CMD.exe", $"/C sc \\\\{remoteMachine} stop \"{serviceName}\"&sc \\\\{remoteMachine} start \"{serviceName}\"");
}
}