0

In C# I have a script, that remotely stops and start service. The problem is, only work stop service.

I need start/stop service, because service must be stopped for something else. It may not be ServiceController, because I have disabled 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();
Przetczak
  • 119
  • 1
  • 11

2 Answers2

1

Oh, I found the solution: Only need Add.Statement between commands.

            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");
Przetczak
  • 119
  • 1
  • 11
0

You could use the ServiceController class like so:

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

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

credits goes to: How to restart service remotely?

Butti
  • 359
  • 2
  • 6