【问题标题】:C# run powershell script (remote start/stop service)C#运行powershell脚本(远程启动/停止服务)
【发布时间】:2023-12-21 04:41:02
【问题描述】:

在 C# 中,我有一个脚本,可以远程停止和启动服务。 问题是,只有停工服务。

我需要启动/停止服务,因为必须为其他事情停止服务。 它可能不是 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();

【问题讨论】:

    标签: c# powershell remote-access


    【解决方案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");
    

    【讨论】:

      【解决方案2】:

      您可以像这样使用 ServiceController 类:

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

      致谢: How to restart service remotely?

      【讨论】:

      • 引用问题:“可能不是ServiceController,因为我禁用了WMI。”