我正在编写一个windows服务,我想传递MSI安装程序的命令行参数。最终目标是使用这些命令行参数让服务知道如何操作。
我已经添加了一个安装程序类,如下所示:
using Quicktech.QuickteckAgentUpdaterServices.Classes;
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace Quicktech.QuickteckAgentUpdaterServices
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public InstallContext myInstallContext;
public ProjectInstaller()
{
InitializeComponent();
}
private void serviceInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
if (Context.Parameters.Count == 0)
{
Console.Write("0");
Global.FlagForUninstall = false;
}
else
{
Console.Write("1");
Global.FlagForUninstall = bool.Parse(Context.Parameters["FLAGFORUNINSTALL"].ToString());
}
}
}
private void serviceProcessInstaller1_BeforeInstall(object sender, InstallEventArgs e)
{
StringDictionary myStringDictionary = myInstallContext.Parameters;
if (myStringDictionary.Count == 0)
{
Console.Write("0");
Global.FlagForUninstall = false;
}
else
{
if (myInstallContext.IsParameterTrue("FlagForUninstall") == true)
{
Console.Write("1");
Global.FlagForUninstall = bool.Parse(myInstallContext.Parameters["FlagForUninstall"].ToString());
}
}
}
}
}
我按如下方式配置了自定义操作:
我调用安装,如下所示:
c:\>msiexec.exe /i "QuickteckAgentUpdaterServiceSetup-x64.msi" /l*v "c:\temp\out.txt" FlagForUninstall=True
当我运行服务并查看在On_Start事件上调用的过程时:
我有以下代码:
if (!Global.FlagForUninstall)
这在installer类中设置。我做错了什么?为什么我看不到命令行参数?
当我查看日志文件时,我看到以下内容:
Property(S): FLAGFORUNINSTALL = true
命令行参数看起来正常工作,但我无法设置FlagForUninstall变量并在执行服务时使用它。有谁能给我指个方向吗?我不需要设置GLOBAL.FlagforUninstall。如果有任何其他方法可以访问Installer.Context属性,我愿意使用该方法。
发布于 2021-06-28 12:38:57
答案其实很简单,我在贴出问题几分钟后就找到了答案。
以下是解决方案:
在本文中看到的install类中,我将AfterInstall更改为:
private void serviceInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
if (Context.Parameters.Count == 0)
{
sc.Start();
}
else
{
sc.Start(new string[] { Context.Parameters["FLAGFORUNINSTALL"].ToString() });
}
}
}
通过将我正在查找的参数(Context.Parameters"FLAGFORUNINSTALL")的值作为字符串Arg传递给service.OnStart(),然后我就能够在我能够说的地方获得所需的效果:
protected override void OnStart(string[] args)
{
if (args != null)
{
if (args[0].ToString().ToUpper() == "TRUE")
Global.FlagForUninstall = true;
else
Global.FlagForUninstall = false;
}
}
https://stackoverflow.com/questions/68157586
复制相似问题