2017-08-24 184 views
0

在C#中我有一個腳本,它可以遠程停止並啓動服務。 問題是,只有工作停止服務。C#運行powershell腳本(遠程啓動/停止服務)

我需要啓動/停止服務,因爲必須停止其他服務。 它可能不是ServiceController,因爲我禁用了WMI。

InitialSessionState initial = InitialSessionState.CreateDefault(); 
Runspace runspace = RunspaceFactory.CreateRunspace(initial); 
runspace.Open(); 
PowerShell ps = PowerShell.Create(); 
ps.Runspace = runspace; 
ps.AddCommand("Get-Service"); //STOP 
ps.AddParameter("ComputerName", textBox7.Text); 
ps.AddParameter("Name", "spooler*"); 
ps.AddCommand("Stop-Service"); 
ps.AddParameter("force"); 

//ps.AddCommand("Remove-Item"); //QUEUE 

ps.AddCommand("Get-Service"); //START 
ps.AddParameter("ComputerName", textBox7.Text); 
ps.AddParameter("Name", "spooler*"); 
ps.AddCommand("Start-Service"); 

ps.Invoke(); 

回答

0

您可以使用ServiceController的類,像這樣:

ServiceController sc = new ServiceController("ArcGIS Server", "192.168.36.22"); 

sc.Start(); 
sc.Stop(); 

學分轉到: How to restart service remotely?

+0

引用問題:「**它可能不是ServiceController **,因爲我禁用了WMI。」 – Fildor

1

哦,我找到了解決辦法: 只需要命令之間Add.Statement。

  ps.AddCommand("Get-Service"); 
      ps.AddParameter("ComputerName", textBox7.Text); 
      ps.AddParameter("Name", "spooler*"); 
      ps.AddCommand("Stop-Service"); 
      ps.AddParameter("force"); 

      ps.AddStatement(); 
      ps.AddCommand("Get-Service"); 
      ps.AddParameter("ComputerName", textBox7.Text); 
      ps.AddParameter("Name", "spooler*"); 
      ps.AddCommand("Start-Service"); 
相關問題