/// <summary>
        /// Installs a service on any machine
        /// </summary>
        /// <param name="machineName">Name of the computer to perform the operation on</param>
        /// <param name="name">The name of the service in the registry</param>
        /// <param name="displayName">The display name of the service in the service manager</param>
        /// <param name="physicalLocation">The physical disk location of the executable</param>
        /// <param name="startMode">How the service starts - usually Automatic</param>
        /// <param name="userName">The user for the service to run under</param>
        /// <param name="password">The password fo the user</param>
        /// <param name="dependencies">Other dependencies the service may have based on the name of the service in the registry</param>
        /// <param name="interactWithDesktop">Should the service interact with the desktop?</param>
        /// <returns>A service return code that defines whether it was successful or not</returns>
        public ServiceReturnCode Install(string machineName, string name, string displayName, string physicalLocation, ServiceStartMode startMode, string userName, string password, string[] dependencies, bool interactWithDesktop)
        {
            const string methodName = "Create";

            //string[] serviceDependencies = dependencies != null ? dependencies.Split(',') : null;
            if (userName.IndexOf('\\') < 0)
            {
                //userName = "******" + userName;
                //UNCOMMENT the line above - it caused issues with color coding in THIS ARTICLE
            }

            try
            {
                object[] parameters = new object[]
                {
                    name,                                              // Name
                    displayName,                                       // Display Name
                    physicalLocation,                                  // Path Name | The Location "E:\somewhere\something"
                    Convert.ToInt32(ServiceType.OwnProcess),           // ServiceType
                    Convert.ToInt32(ServiceErrorControl.UserNotified), // Error Control
                    startMode.ToString(),                              // Start Mode
                    interactWithDesktop,                               // Desktop Interaction
                    userName,                                          // StartName | Username
                    password,                                          // StartPassword |Password
                    null,                                              // LoadOrderGroup | Service Order Group
                    null,                                              // LoadOrderGroupDependencies | Load Order Dependencies
                    dependencies                                       // ServiceDependencies
                };
                return((ServiceReturnCode)_wmi.InvokeStaticMethod(machineName, CLASS_NAME, methodName, parameters));
            }
            catch
            {
                return(ServiceReturnCode.UnknownFailure);
            }
        }
示例#2
0
        /// <summary>
        ///     This routine updates the start mode of the provided service.
        ///     Add Reference to System.Management .net Assembly
        /// </summary>
        /// <param name="serviceName">Name of the service to be updated</param>
        /// <param name="serviceStart"></param>
        /// <param name="errorMsg">If applicable, error message assoicated with exception</param>
        /// <returns>Success or failure.  False is returned if service is not found.</returns>
        public bool SetServiceStartupMode(string serviceName, ServiceStartMode serviceStart, out string errorMsg)
        {
            uint success = 1;

            errorMsg = string.Empty;
            string startMode = serviceStart.ToString();

            string filter =
                String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName);

            var query = new ManagementObjectSearcher(filter);

            try
            {
                ManagementObjectCollection services = query.Get();

                foreach (ManagementObject service in services)
                {
                    ManagementBaseObject inParams =
                        service.GetMethodParameters("ChangeStartMode");
                    inParams["startmode"] = startMode;

                    ManagementBaseObject outParams =
                        service.InvokeMethod("ChangeStartMode", inParams, null);
                    success = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value);
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                throw;
            }
            return(success == 0);
        }
示例#3
0
        //private char NULL_VALUE = char(0);
        public static ServiceReturnCode Create(string machineName, string serviceName, string serviceDisplayName,
                                               string serviceLocation, ServiceStartMode startMode, string userName,
                                               string password, string[] dependencies)
        {
            if (userName != null && userName.IndexOf('\\') < 0)
            {
                userName = "******" + userName;
            }

            try
            {
                const string methodName = "Create";

                var parameters = new object[]
                                     {
                                         serviceName, // Name
                                         serviceDisplayName, // Display Name
                                         serviceLocation, // Path Name | The Location "E:\somewhere\something"
                                         Convert.ToInt32(ServiceType.OwnProcess), // ServiceType
                                         Convert.ToInt32(ErrorControl.UserNotified), // Error Control
                                         startMode.ToString(), // Start Mode
                                         false, // Desktop Interaction
                                         userName, // StartName | Username
                                         password, // StartPassword |Password
                                         null, // LoadOrderGroup | Service Order Group
                                         null, // LoadOrderGroupDependencies | Load Order Dependencies
                                         dependencies //  ServiceDependencies
                                     };
                return (ServiceReturnCode) WmiHelper.InvokeStaticMethod(machineName, CLASSNAME, methodName, parameters);
            }
            catch
            {
                return ServiceReturnCode.UnknownFailure;
            }
        }
示例#4
0
 private static string GetLocalizedStartType(ServiceStartMode startMode)
 {
     if (startMode == ServiceStartMode.Boot)
     {
         return(Resources.wox_plugin_service_start_mode_boot);
     }
     else if (startMode == ServiceStartMode.System)
     {
         return(Resources.wox_plugin_service_start_mode_system);
     }
     else if (startMode == ServiceStartMode.Automatic)
     {
         return(Resources.wox_plugin_service_start_mode_automatic);
     }
     else if (startMode == ServiceStartMode.Manual)
     {
         return(Resources.wox_plugin_service_start_mode_manual);
     }
     else if (startMode == ServiceStartMode.Disabled)
     {
         return(Resources.wox_plugin_service_start_mode_disabled);
     }
     else
     {
         return(startMode.ToString());
     }
 }
 private bool SetStartModeViaManagementObject(ServiceStartMode startMode)
 {
     using (var mo = new ManagementObject(string.Format("Win32_Service.Name=\"{0}\"", _serviceController.ServiceName)))
     {
         var result = mo.InvokeMethod("ChangeStartMode", new object[] { startMode.ToString() });
         return(result.ToString() != "2"); //Access Denied
     }
 }
        private static void setServiceStartMode(string serviceName, ServiceStartMode startMode)
        {
            using ManagementObject wmiService = getWmiService(serviceName);
            ManagementBaseObject reqParams = wmiService.GetMethodParameters("ChangeStartMode");

            reqParams["StartMode"] = startMode.ToString();
            wmiService.InvokeMethod("ChangeStartMode", reqParams, null);
        }
示例#7
0
 public static void SetStartupType(this ServiceController controller, ServiceStartMode newType)
 {
     using (var wmiManagementObject = new ManagementObject(new ManagementPath(string.Format("Win32_Service.Name='{0}'", controller.ServiceName))))
     {
         var parameters = new object[1];
         parameters[0] = newType.ToString();
         wmiManagementObject.InvokeMethod("ChangeStartMode", parameters);
     }
 }
 public static void SetStartupType(this ServiceController controller, ServiceStartMode newType)
 {
     using (var wmiManagementObject = controller.GetNewWmiManagementObject())
     {
         var parameters = new object[1];
         parameters[0] = newType.ToString();
         wmiManagementObject.InvokeMethod("ChangeStartMode", parameters);
     }
 }
        public static ServiceReturnCode CreateService(string serviceName, string machineName, string displayName, string pathName, ServiceStartMode startMode,
                                                      string startName = null, string password = null, string parameters = null,
                                                      WindowsServiceType serviceType      = WindowsServiceType.OwnProcess, ErrorControlAction errorControl = ErrorControlAction.UserIsNotified,
                                                      bool interactWithDesktop            = false, string loadOrderGroup = null,
                                                      string[] loadOrderGroupDependencies = null, string[] svcDependencies = null)
        {
            ServiceReturnCode result = ServiceReturnCode.UnknownFailure;

            ServiceUtilWmiHelper helper  = new ServiceUtilWmiHelper(machineName);
            ManagementClass      mc      = helper.GetManagementClass("Win32_Service");
            ManagementBaseObject inparms = mc.GetMethodParameters("Create");
            string execPath = pathName;

            if (startMode == ServiceStartMode.Unchanged)
            {
                startMode = ServiceStartMode.Automatic;
            }

            if (!string.IsNullOrEmpty(parameters))
            {
                execPath = string.Format("{0} {1}", pathName, parameters);
            }

            inparms["Name"]                       = serviceName;
            inparms["DisplayName"]                = displayName;
            inparms["PathName"]                   = execPath;
            inparms["ServiceType"]                = serviceType;
            inparms["ErrorControl"]               = errorControl;
            inparms["StartMode"]                  = startMode.ToString();
            inparms["DesktopInteract"]            = interactWithDesktop;
            inparms["StartName"]                  = startName;
            inparms["StartPassword"]              = password;
            inparms["LoadOrderGroup"]             = loadOrderGroup;
            inparms["LoadOrderGroupDependencies"] = loadOrderGroupDependencies;
            inparms["ServiceDependencies"]        = svcDependencies;

            try
            {
                ManagementBaseObject mbo = mc.InvokeMethod("Create", inparms, null);
                result = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());

                if (result == ServiceReturnCode.Success)
                {
                    UpdateServiceDescriptionWithVersion(serviceName, machineName, pathName);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
示例#10
0
        private ServiceReturnCode Install(string machineName, string name, string displayName, string physicalLocation, ServiceStartMode startMode, string userName, string password, string[] dependencies, bool interactWithDesktop, string installingUser, string installingUserPassword)
        {
            bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable);

            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Attempting to install the '{0}' service to the '{1}' machine", displayName, machineName));
            if (userName.IndexOf('\\') < 0)
            {
                userName = "******" + userName;
            }

            try
            {
                string path = targetLocal ? "\\root\\CIMV2" : string.Format(CultureInfo.InvariantCulture, "\\\\{0}\\root\\CIMV2", machineName);

                ManagementClass wmi = new ManagementClass(path, "Win32_Service", null);

                if (!targetLocal)
                {
                    wmi.Scope.Options.Username = installingUser;
                    wmi.Scope.Options.Password = installingUserPassword;
                }

                object[] paramList = new object[]
                {
                    name,
                    displayName,
                    physicalLocation,
                    Convert.ToInt32(ServiceTypes.OwnProcess, CultureInfo.InvariantCulture),
                    Convert.ToInt32(ServiceErrorControl.UserNotified, CultureInfo.InvariantCulture),
                    startMode.ToString(),
                    interactWithDesktop,
                    userName,
                    password,
                    null,
                    null,
                    dependencies
                };

                // Execute the method and obtain the return values.
                object result     = wmi.InvokeMethod("Create", paramList);
                int    returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture);
                return((ServiceReturnCode)returnCode);
            }
            catch (Exception ex)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Install Service [{0} on {1}] failed with error '{2}'", this.ServiceDisplayName, this.MachineName, ex.Message));
                return(ServiceReturnCode.UnknownFailure);
            }
        }
        /// <summary>
        /// Sets the StartMode of a Windows service.
        /// </summary>
        /// <param name="serviceName">The internal service name. Ex:"Print Spooler" is "Spooler".</param>
        /// <param name="machineName">The server on which the service is running.</param>
        /// <param name="startMode">The value to set.</param>
        /// <returns>Enumerated value as returned from Wmi call.</returns>
        public static ServiceReturnCode ChangeStartMode(string serviceName, string machineName, ServiceStartMode startMode)
        {
            ServiceReturnCode result = ServiceReturnCode.UnknownFailure;

            ManagementObjectCollection services = GetServicesByServiceName(serviceName, machineName);

            foreach (ManagementObject service in services)
            {
                ManagementBaseObject inparms = service.GetMethodParameters("ChangeStartMode");
                inparms["StartMode"] = startMode.ToString();
                ManagementBaseObject mbo = service.InvokeMethod("ChangeStartMode", inparms, null);
                result = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());
            }

            return(result);
        }
示例#12
0
        /// <summary>
        /// Set start mode of the service.
        /// </summary>
        /// <param name="start"></param>
        /// <returns></returns>
        public ServiceCreateTask StartMode(ServiceStartMode start)
        {
            string arg;

            switch (start)
            {
            case ServiceStartMode.DelayedAuto:
            {
                arg = "Delayed-Auto";
                break;
            }

            default:
            {
                arg = start.ToString();
                break;
            }
            }

            WithArguments($"start={arg}");
            return(this);
        }
示例#13
0
        public static void SafeChangeStartMode(string serviceName, ServiceStartMode mode)
        {
            ServiceController service = GetService(serviceName);

            if (service == null)
            {
                return;
            }

            string strMode = mode.ToString().ToUpper().TrimStart("SERVICESTARTMODE.");

            try
            {
                if (WinSrvHelper.GetStartupType(service) != strMode)
                {
                    ChangeStartMode(service, mode);  // 将服务设置为 自动启动
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex);
            }
        }
示例#14
0
        /// <summary>
        /// Installs a service on any machine
        /// </summary>
        /// <param name="machineName">Name of the computer to perform the operation on</param>
        /// <param name="serviceName">The name of the service in the registry</param>
        /// <param name="displayName">The display name of the service in the service manager</param>
        /// <param name="physicalLocation">The physical disk location of the executable</param>
        /// <param name="startMode">How the service starts - usually Automatic</param>
        /// <param name="userName">The user for the service to run under</param>
        /// <param name="password">The password fo the user</param>
        /// <param name="dependencies">Other dependencies the service may have based on the name of the service in the registry</param>
        /// <param name="interactWithDesktop">Should the service interact with the desktop?</param>
        /// <returns>A service return code that defines whether it was successful or not</returns>
        public ServiceReturnCode Install(string machineName, string serviceName, string displayName, string physicalLocation, ServiceStartMode startMode, string userName, string password, string[] dependencies, bool interactWithDesktop)
        {
            if (string.IsNullOrEmpty(userName))
            {
                userName = "******";
            }

            if (userName.IndexOf('\\') < 0)
            {
                userName = "******" + userName;
            }

            try
            {
                object[] parameters = new object[]
                {
                    serviceName,                                                             // Name
                    displayName,                                                             // Display Name
                    physicalLocation,                                                        // Path Name | The Location "E:\somewhere\something"
                    Convert.ToInt32(ServiceType.OwnProcess),                                 // ServiceType
                    Convert.ToInt32(ServiceErrorControl.UserNotified),                       // Error Control
                    startMode.ToString(),                                                    // Start Mode
                    interactWithDesktop,                                                     // Desktop Interaction
                    userName,                                                                // StartName | Username
                    password,                                                                // StartPassword |Password
                    null,                                                                    // LoadOrderGroup | Service Order Group
                    null,                                                                    // LoadOrderGroupDependencies | Load Order Dependencies
                    dependencies                                                             // ServiceDependencies
                };
                return((ServiceReturnCode)this.wmi.InvokeStaticMethod(machineName, "Win32_Service", "Create", parameters));
            }
            catch
            {
                return(ServiceReturnCode.UnknownFailure);
            }
        }
        public ServiceReturnCode ChangeStartMode(string svcName, ServiceStartMode startMode)
        {
            ServiceReturnCode retCode = ServiceReturnCode.UnknownFailure;
            string            host    = Scope.Path.Server;

            try
            {
                ObjectQuery query = new ObjectQuery("SELECT Name,ProcessId,State,Started, StartMode FROM Win32_service WHERE name='" + svcName + "'");
                ManagementObjectCollection queryCollection = Query(query, WmiPath.Root);

                foreach (ManagementObject service in queryCollection)
                {
                    ManagementBaseObject mboIn = service.GetMethodParameters("ChangeStartMode");
                    mboIn["StartMode"] = startMode.ToString();
                    ManagementBaseObject mbo = service.InvokeMethod("ChangeStartMode", mboIn, null);
                    retCode = (ServiceReturnCode)Enum.Parse(typeof(ServiceReturnCode), mbo["ReturnValue"].ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(retCode);
        }
示例#16
0
        //private char NULL_VALUE = char(0);

        public static ServiceReturnCode Create(string machineName, string serviceName, string serviceDisplayName,
                                               string serviceLocation, ServiceStartMode startMode, string userName,
                                               string password, string[] dependencies)
        {
            if (userName != null && userName.IndexOf('\\') < 0)
            {
                userName = "******" + userName;
            }

            try
            {
                const string methodName = "Create";


                var parameters = new object[]
                {
                    serviceName,                                // Name
                    serviceDisplayName,                         // Display Name
                    serviceLocation,                            // Path Name | The Location "E:\somewhere\something"
                    Convert.ToInt32(ServiceType.OwnProcess),    // ServiceType
                    Convert.ToInt32(ErrorControl.UserNotified), // Error Control
                    startMode.ToString(),                       // Start Mode
                    false,                                      // Desktop Interaction
                    userName,                                   // StartName | Username
                    password,                                   // StartPassword |Password
                    null,                                       // LoadOrderGroup | Service Order Group
                    null,                                       // LoadOrderGroupDependencies | Load Order Dependencies
                    dependencies                                //  ServiceDependencies
                };
                return((ServiceReturnCode)WmiHelper.InvokeStaticMethod(machineName, CLASSNAME, methodName, parameters));
            }
            catch
            {
                return(ServiceReturnCode.UnknownFailure);
            }
        }
示例#17
0
        private ServiceReturnCode Install(string machineName, string name, string displayName, string physicalLocation, ServiceStartMode startMode, string userName, string password, string[] dependencies, bool interactWithDesktop, string installingUser, string installingUserPassword)
        {
            bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable);

            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Attempting to install the '{0}' service to the '{1}' machine", displayName, machineName));
            if (userName.IndexOf('\\') < 0)
            {
                userName = "******" + userName;
            }

            try
            {
                string path = targetLocal ? "\\root\\CIMV2" : string.Format(CultureInfo.InvariantCulture, "\\\\{0}\\root\\CIMV2", machineName);

                ManagementClass wmi = new ManagementClass(path, "Win32_Service", null);

                if (!targetLocal)
                {
                    wmi.Scope.Options.Username = installingUser;
                    wmi.Scope.Options.Password = installingUserPassword;
                }

                object[] paramList = new object[]
                {
                  name, 
                  displayName, 
                  physicalLocation, 
                  Convert.ToInt32(ServiceTypes.OwnProcess, CultureInfo.InvariantCulture), 
                  Convert.ToInt32(ServiceErrorControl.UserNotified, CultureInfo.InvariantCulture),
                  startMode.ToString(), 
                  interactWithDesktop, 
                  userName, 
                  password, 
                  null, 
                  null, 
                  dependencies
              };

                // Execute the method and obtain the return values.
                object result = wmi.InvokeMethod("Create", paramList);
                int returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture);
                return (ServiceReturnCode)returnCode;
            }
            catch (Exception ex)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Install Service [{0} on {1}] failed with error '{2}'", this.ServiceDisplayName, this.MachineName, ex.Message));
                return ServiceReturnCode.UnknownFailure;
            }
        }
示例#18
0
        /// <summary>
        /// This routine updates the start mode of the provided service.
        /// Add Reference to System.Management .net Assembly
        /// </summary>
        /// <param name="serviceName">Name of the service to be updated</param>
        /// <param name="serviceStart"></param>
        /// <param name="errorMsg">If applicable, error message assoicated with exception</param>
        /// <returns>Success or failure.  False is returned if service is not found.</returns>
        private static bool SetServiceStartupMode(string serviceName, ServiceStartMode serviceStart, out string errorMsg)
        {
            uint success = 1;
            errorMsg = string.Empty;
            string startMode = serviceStart.ToString();

            string filter =
                String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName);

            var query = new ManagementObjectSearcher(filter);

            try
            {
                ManagementObjectCollection services = query.Get();

                foreach (ManagementObject service in services)
                {
                    ManagementBaseObject inParams = service.GetMethodParameters("ChangeStartMode");
                    inParams["startmode"] = startMode;

                    ManagementBaseObject outParams =
                        service.InvokeMethod("ChangeStartMode", inParams, null);
                    if (outParams != null) success = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value);
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                throw;
            }
            return (success == 0);
        }
示例#19
0
        /// <summary>
        ///     Installs the service(s) in the specified assembly.
        /// </summary>
        /// <param name="path">
        ///     A string containing the path to the service assembly.
        /// </param>
        /// <param name="startMode">
        ///     An enumeration that describes how and when this service is started.
        /// </param>
        /// <param name="account">
        ///     An enumeration that describes the type of account under which the service will run.
        /// </param>
        /// <param name="credentials">
        ///     The user credentials of the account under which the service will run.
        /// </param>
        /// <param name="parameters">
        ///     A dictionary of parameters passed to the service's installer.
        /// </param>
        public static void InstallService(string path, ServiceStartMode startMode, ServiceAccount account, NetworkCredential credentials, StringDictionary parameters)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("The specified path parameter is invalid.");
            }

            string filename = Path.GetFileNameWithoutExtension(path);

            try
            {
                // Initialize the service installer
                Assembly serviceAssembly  = Assembly.LoadFrom(path);
                var      serviceInstaller = new AssemblyInstaller(serviceAssembly, null);

                var commandLine = new ArrayList
                {
                    string.Format("StartMode={0}", startMode.ToString("g"))
                };

                // Set the service start mode

                // Set the service account
                switch (account)
                {
                case ServiceAccount.LocalService:
                case ServiceAccount.NetworkService:
                case ServiceAccount.LocalSystem:
                {
                    commandLine.Add(string.Format("Account={0}", account.ToString("g")));
                    break;
                }

                case ServiceAccount.User:
                {
                    commandLine.Add(string.Format("Account={0}", CredentialHelper.GetFullyQualifiedName(credentials)));
                    commandLine.Add(string.Format("Password={0}", credentials.Password));
                    break;
                }
                }

                // Set any parameters
                if (parameters != null)
                {
                    foreach (string key in parameters.Keys)
                    {
                        commandLine.Add(string.Format("{0}={1}", key, parameters[key]));
                    }
                }

                // Initialize the service installer
                serviceInstaller.CommandLine = ( string[] )commandLine.ToArray(typeof(string));

                // Initialize the base installer
                var transactedInstaller = new TransactedInstaller( );
                transactedInstaller.Installers.Add(serviceInstaller);
                transactedInstaller.Context = new InstallContext(string.Format("{0}.log", filename), ( string[] )commandLine.ToArray(typeof(string)));

                // Install the service
                var savedState = new Hashtable( );
                transactedInstaller.Install(savedState);
            }
            catch (Exception exception)
            {
                throw new Exception("Unable to install the specified service.", exception);
            }
        }
示例#20
0
        /// <summary>
        /// See http://www.codeproject.com/Articles/7665/Extend-ServiceController-class-to-change-the-Start
        /// </summary>
        /// <param name="serviceController"></param>
        /// <param name="mode"></param>
        private void ChangeStartMode(ServiceController serviceController, ServiceStartMode mode)
        {
            /*if (value != "Automatic" && value != "Manual" && value != "Disabled")
                throw new Exception("The valid values are Automatic, Manual or Disabled");*/

            //construct the management path
            Console.WriteLine("change service " + serviceController.ServiceName + " to " + mode.ToString());
            string path = "Win32_Service.Name='" + serviceController.ServiceName + "'";
            ManagementPath p = new ManagementPath(path);
            //construct the management object
            ManagementObject ManagementObj = new ManagementObject(p);
            //we will use the invokeMethod method of the ManagementObject class
            object[] parameters = new object[1];
            parameters[0] = mode.ToString();
            object result = ManagementObj.InvokeMethod("ChangeStartMode", parameters);

            Console.WriteLine("result: " + result);
        }