启动服务后脚本抛出错误

Script throwing an error after starting the service

我已经将下面的代码写到 start 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

执行上述脚本后,出现以下错误:

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

我看到服务 Running 成功了,为什么即使服务已正确启动它也会抛出错误?

我正在使用 poweshell 5

继续我的评论,尝试:

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