2013-02-14 70 views
-3

我需要将可执行文件安装为服务,并且需要使用用C#编写的PowerShell cdmlet来执行此操作。实质上,我需要创建所需的注册表项等来定义服务(包括要运行的可执行文件 - 一种srvany.exe)。C#实现新服务cmdlet

我还需要能够定义此服务的登录身份(凭证)。

TIA,汉斯

有什么我想这么远。我一直在寻找ServiceProcessInstaller和ServiceProcessInstaller类,但他们错过了定义'external'可执行文件的可能性。

public partial class MyServiceInstaller : Installer 
    { 
     public MyServiceInstaller() 
     { 
      IDictionary saveState = null; 
      this.Installers.Clear(); 
      ServiceProcessInstaller spi = new ServiceProcessInstaller(); 
      ServiceInstaller si = new ServiceInstaller(); 
      spi.Account = ServiceAccount.LocalSystem; 
      spi.Username = null; 
      spi.Password = null; 
      si.ServiceName = "MyService"; 
      si.DisplayName = "MyService"; 
      si.StartType = ServiceStartMode.Automatic; 
      si.Description = "MyService - I wish...."; 

      spi.Installers.Add(si); 
      this.Installers.Add(spi); 
      this.Install(saveState); 
     } 
    } 

被困在这里,因为我找不到添加可执行文件的路径(服务的ImagePath)的方式

+3

,而['你有什么tried'(http://mattgemmell.com/2008/12/08/what-have-you-tried/)?你遇到过什么特别的困难?我在你的问题中看到的所有内容都是'我需要...',但是我没有看到'这是我尝试的代码,但是...' – 2013-02-14 17:33:31

+0

欢迎来到SO。请查看[常见问题]和[关于]页面,查看哪些问题最受欢迎。 – 2013-02-14 17:50:19

回答

0

嗯,我有下面的代码工作,我只是想知道有没有更“天然”方式做到这一点。

   Command psc = new Command("New-Service"); 
       psc.Parameters.Add("Name", svcName); 
       psc.Parameters.Add("BinaryPathName", svcExec); 
       psc.Parameters.Add("DisplayName", svcName); 
       psc.Parameters.Add("Description", svcDesc); 
       psc.Parameters.Add("StartupType", "Automatic"); 
       WriteVerbose("Verifying service account"); 
       if (Account == null) { WriteVerbose("- Using LocalSystem account"); } 
       else { psc.Parameters.Add("Credential", crd); } 
       WriteVerbose("Installing service"); 
       Pipeline pipeline = Runspace.DefaultRunspace.CreateNestedPipeline(); 
       pipeline.Commands.Add(psc); 
       Collection<PSObject> results = pipeline.Invoke(); 
0

由于Brad Bruce我发现我的需要在:How do I install a C# Windows service without creating an installer?

我做了一个小的调整到IntegratedServiceInstaller类,调用“SINST.Install(状态)”,将产生3行输出

的调用SINST.Uninstall(空)

Installing service 'ServiceName'... 
Service 'ServiceName' has been successfully installed. 
Creating EventLog source 'ServiceName' in log Application... 

类似的线被写入到控制台我抑制由该redir的输出ecting输出到Stream.Null

System.IO.StreamWriter sw = new System.IO.StreamWriter(Stream.Null); 
    System.IO.TextWriter tmp = Console.Out; 
    Console.SetOut(sw); 
    try { SINST.Install(state); } 
    catch (Exception Ex) { Console.SetOut(tmp); Console.WriteLine(Ex.Message); } 
    finally { Console.SetOut(tmp); }