简体   繁体   中英

Script throwing an error after starting the service

I have written the below code to start the service :

invoke-command -cn $server -Credential $cred -ScriptBlock {
param($svc) 
if((get-service $svc).status -ne "running") {
    get-service $svc| start-service     
    set-service $svc -StartupType Automatic
    (get-service $svc).waitforstatus('running')  
 }
 get-service $svc| select ServiceName
} -ArgumentList $svc

After executing the above script, I am getting below error:

Status         : Running
StartType      : Automatic
ServiceName    : svcname
PSComputerName : host1

+     invoke-command -cn $server -Credential $cred -ScriptBlock {
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
    + FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand

I see service is Running successfully so why it is throwing an error even when the service was started correctly?

I am using poweshell 5

Continuing from my comments, try:

Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
    param($svc) 
    $theService = Get-Service -Name $svc
    if($theService.Status -ne 'Running') {
        if ($theService.Status -ne 'Stopped') { $theService | Stop-Service -Force }
        $theService | Set-Service -StartupType Automatic
        ($theService | Start-Service -PassThru).WaitForStatus('Running')
     }
     $theService | Select-Object ServiceName
} -ArgumentList $svc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM