4

I am trying to start/stop services via a job in powershell. In testing this on my local machine, the job will go to a completed state but the service will not change its status. Is there a way to get a better view of what my job did?

Here is the code:

$service = 'MSSQL$SQLEXPRESS'
$server = 'myPC'
$myJob = Start-Job -Scriptblock {Get-Service -Name $args[0] -computername $args[1] | Set-Service -Status Running} -ArgumentList @($service,$server)
sleep -Seconds 10
get-job

The SQL SQL (EXPRESS) service does not start when I run that snippet.

However, if I ran the following from the elevated shell, it would start:

Get-Service -Name $service -computername $server | Set-Service -Status Running

When I run Get-Job, here is what I see...

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
10     Job10           BackgroundJob   Completed     True            localhost            Get-Service -Name $arg...

These are both running from an elevated shell, so I definitely have permission to start/stop the service.

Christopher
  • 790
  • 12
  • 30

1 Answers1

5

Use Get-Job | Receive-Job to see the output from your jobs (including any errors).

Or (to be more specific) for the job you created:

$myjob | Receive-Job

Also FYI, rather than Start-Sleep, you could do $myjob | Wait-Job to wait for the job to complete before continuing code execution. You can also:

$myjob | Wait-Job | Receive-Job
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • 1
    Thanks! I was able to find that my issue was "get-service : Cannot open Service Control Manager on computer. This operation might require other privileges.". Strange that the job would still go to a completed state with such an error. But thanks for the answer! – Christopher Jun 28 '17 at 13:58