/// <summary> /// Retrieve state of remote Windows Service /// </summary> /// <param name="svcName"></param> /// <returns></returns> public static ServiceManagementServiceState LocalGetServiceState(string svcName) { ServiceManagementServiceState toReturn = ServiceManagementServiceState.Stopped; string _state = string.Empty; string objPath = string.Format("Win32_Service.Name='{0}'", svcName); using (ManagementObject service = _local_wmi_base.GetLocalManagementObject(objPath)) { try { _state = service.Properties["State"].Value.ToString().Trim(); switch (_state) { case "Running": toReturn = ServiceManagementServiceState.Running; break; case "Stopped": toReturn = ServiceManagementServiceState.Stopped; break; case "Paused": toReturn = ServiceManagementServiceState.Paused; break; case "Start Pending": toReturn = ServiceManagementServiceState.StartPending; break; case "Stop Pending": toReturn = ServiceManagementServiceState.StopPending; break; case "Continue Pending": toReturn = ServiceManagementServiceState.ContinuePending; break; case "Pause Pending": toReturn = ServiceManagementServiceState.PausePending; break; } } catch (Exception ex) { throw ex; } } return(toReturn); }
public static void LocalKillStopServices(string[] _services) { foreach (string _srv in _services) { int _tries = 0; int _connect_tries = 0; while (_tries++ < 3) { ServiceManagementServiceState _state = ServiceManagementServiceState.Running; while (_connect_tries++ < 3) { try { _state = LocalGetServiceState(_srv); } catch (Exception _ex) { Thread.Sleep(new TimeSpan(0, 0, 10)); if (_connect_tries > 3) { throw new Exception($"{_srv} not found after 3 tries {_ex.GetBaseException().Message}"); } continue; } } if (_state != ServiceManagementServiceState.Stopped) { LocalStopService(_srv); LocalKillProcess($"{ _srv.Replace("-", "")}.exe"); } else { break; } Thread.Sleep(new TimeSpan(0, 0, 5)); if (_tries > 3) { throw new Exception($"{_srv} did not stop after 3 tries on localhost"); } } } }
public async Task KillStopRemoteServicesAsync(string[] _services) { foreach (string _srv in _services) { int _tries = 0; int _connect_tries = 0; while (_tries++ < 3) { ServiceManagementServiceState _state = ServiceManagementServiceState.Running; while (_connect_tries++ < 3) { try { _state = await GetServiceStateAsync(_srv); } catch (Exception _ex) { Thread.Sleep(new TimeSpan(0, 0, 10)); if (_connect_tries > 3) { throw new Exception($"{_srv} not found after 3 tries on #{_local_computeresource_context.ComputeResource.Hostname} : {_ex.GetBaseException().Message}"); } continue; } } if (_state != ServiceManagementServiceState.Stopped) { await StopServiceAsync(_srv); await KillProcessAsync($"{ _srv.Replace("-", "")}.exe"); } else { break; } Thread.Sleep(new TimeSpan(0, 0, 5)); if (_tries > 3) { throw new Exception($"{_srv} did not stop after 3 tries on #{_local_computeresource_context.ComputeResource.Hostname}"); } } } }