Dot-Net

使用 InstallUtil 並靜默設置 Windows 服務登錄使用者名/密碼

  • September 26, 2008

我需要使用 InstallUtil 安裝 C# windows 服務。我需要設置服務登錄憑據(使用者名和密碼)。所有這些都需要默默地完成。

有沒有辦法做這樣的事情:

installutil.exe myservice.exe /customarg1=username /customarg2=password

向我的同事(布魯斯·埃迪)致敬。他找到了一種我們可以進行此命令行呼叫的方法:

installutil.exe /user=uname /password=pw myservice.exe

它是通過覆蓋安裝程序類中的 OnBeforeInstall 來完成的:

namespace Test
{
   [RunInstaller(true)]
   public class TestInstaller : Installer
   {
       private ServiceInstaller serviceInstaller;
       private ServiceProcessInstaller serviceProcessInstaller;

       public OregonDatabaseWinServiceInstaller()
       {
           serviceInstaller = new ServiceInstaller();
           serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
           serviceInstaller.ServiceName = "Test";
           serviceInstaller.DisplayName = "Test Service";
           serviceInstaller.Description = "Test";
           serviceInstaller.StartType = ServiceStartMode.Automatic;
           Installers.Add(serviceInstaller);

           serviceProcessInstaller = new ServiceProcessInstaller();
           serviceProcessInstaller.Account = ServiceAccount.User; 
           Installers.Add(serviceProcessInstaller);
       }

       public string GetContextParameter(string key)
       {
           string sValue = "";
           try
           {
               sValue = this.Context.Parameters[key].ToString();
           }
           catch
           {
               sValue = "";
           }
           return sValue;
       }


       // Override the 'OnBeforeInstall' method.
       protected override void OnBeforeInstall(IDictionary savedState)
       {
           base.OnBeforeInstall(savedState);

           string username = GetContextParameter("user").Trim();
           string password = GetContextParameter("password").Trim();

           if (username != "")
               serviceProcessInstaller.Username = username;
           if (password != "")
               serviceProcessInstaller.Password = password;
       }
   }
}

比上面的文章更簡單且安裝程序中沒有額外程式碼的方法是使用以下內容:

installUtil.exe /username=domain\username /password=password /unattended C:\My.exe

只要確保您使用的帳戶是有效的。如果沒有,您將收到“帳戶名稱和安全 ID 之間的映射未完成”異常

引用自:https://stackoverflow.com/questions/140054