C# Change service start mode
Here is some code to Change the StartMode on one or more services using C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
string ns = @"root\cimv2"; string query = "select * from Win32_Service"; string compname = "ComputerName"; ConnectionOptions options = new ConnectionOptions(); ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\{1}", compname, ns), options); scope.Connect(); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query)); ManagementObjectCollection retObjectCollection = searcher.Get(); foreach (ManagementObject mo in searcher.Get()) { name = mo.Properties["Name"].Value.ToString().Trim().ToLower(); state = mo.Properties["State"].Value.ToString().Trim(); startmode = mo.Properties["StartMode"].Value.ToString().Trim(); switch (name) { case "service1": changemode(mo, "Manual"); break; case "winmgmt": changemode(mo, "Auto"); break; } } private void changemode(ManagementObject mo, string startmode) { ManagementBaseObject inParams = mo.GetMethodParameters("ChangeStartMode"); inParams["startmode"] = startmode; ManagementBaseObject outParams = mo.InvokeMethod("ChangeStartMode", inParams, null); startmode = mo.Properties["StartMode"].Value.ToString().Trim(); } |
C# Start service on remote machine
Here is a simple method to start a service on a remote system using C#. Call the method using
1 |
string status = servicestart("computerName", "Service"); |
Method will attempt to change the status and return the current Status
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
private string servicestart(string compname, string service) { ServiceController sc = new ServiceController(); sc.ServiceName = service; sc.MachineName = compname; string result = sc.Status.ToString(); if (sc.Status == ServiceControllerStatus.Stopped) { try { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); result = sc.Status.ToString(); } catch (InvalidOperationException) { // do something } } return result; } |