简体   繁体   English

如何通过ManagementObject和InvokeMethod()将参数传递给Windows服务

[英]How to pass parameters to windows service via ManagementObject and InvokeMethod()

Depending on the state, necessary to call the start of the windows service with parameters. 根据状态,需要使用参数调用Windows服务的启动。 The call used ManagementObject and InvokeMethod. 该调用使用了ManagementObject和InvokeMethod。 Is it possible to pass parameters into the service Onstart() method? 是否可以将参数传递到服务的Onstart()方法中?

_sr.InvokeMethod("StartService", "Some Parameters"); --> 

protected override   void OnStart(string[] args)
 {
  args // <-catch here
 }  

Not sure you can with ManagmentObject , however you probably can with ServiceController Class 不知道可以使用ManagmentObject ,但是可以使用ServiceController

ServiceController.Start Method ServiceController.Start方法

Starts a service, passing the specified arguments. 启动服务,并传递指定的参数。

ServiceController sc  = new ServiceController();
sc.ServiceName = "Alerter";
Console.WriteLine("The Alerter service status is currently set to {0}", 
                   sc.Status.ToString());

if (sc.Status == ServiceControllerStatus.Stopped)
{
   // Start the service if the current status is stopped.

   Console.WriteLine("Starting the Alerter service...");
   try 
   {
      // Start the service, and wait until its status is "Running".
      sc.Start(new []{"args","here","Yehaa");
      sc.WaitForStatus(ServiceControllerStatus.Running);

      // Display the current service status.
      Console.WriteLine("The Alerter service status is now set to {0}.", 
                         sc.Status.ToString());
   }
   catch (InvalidOperationException)
   {
      Console.WriteLine("Could not start the Alerter service.");
   }
}

Service 服务

public partial class MyService : ServiceBase { 公共局部类MyService:ServiceBase {

    public MyService(uint port)
    {
        InitializeComponent();
    }

    // This method gets called with `sc start`
    // and can be used to override arguments during startup
    protected override void OnStart(string[] args)
    {
        // Do stuff with args
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM