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
CodePudding user response:
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