2013-02-14 71 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); }