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.
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