使用InstallUtil并静默设置Windows服务登录用户名/密码
时间:2020-03-06 14:47:23 来源:igfitidea点击:
我需要使用InstallUtil来安装Cwindows服务。我需要设置服务登录凭据(用户名和密码)。所有这些都需要静默完成。
有没有办法做这样的事情:
installutil.exe myservice.exe /customarg1=username /customarg2=password
解决方案
不,installutil不支持该功能。
当然,如果我们编写了安装程序;通过自定义操作,我们就可以将其作为MSI的一部分或者通过installutil来使用。
向我的同事(Bruce Eddy)喝彩。他找到了一种可以进行此命令行调用的方法:
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;
}
}
}
我们还可以使用以下命令强制服务以"用户"身份运行
ServiceProcessInstaller :: Account = ServiceAccount.User;
在安装服务期间,将弹出一个询问" [域]用户,密码"的弹出窗口。
public class MyServiceInstaller : Installer
{
/// Public Constructor for WindowsServiceInstaller
public MyServiceInstaller()
{
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.User; // and not LocalSystem;
....
比上面的帖子更简单且安装程序中没有多余代码的方法是使用以下命令:
installUtil.exe /username=domain\username /password=password /unattended C:\My.exe
只要确保我们使用的帐户是有效的即可。否则,我们将收到"帐户名和安全标识之间未完成映射"的异常

