but few servers it won't work manaul go to each server kill that service and then start the service after that service running for service kill
I'm sorry but I don't understand what you are trying tell us. When it doesn't work, what error do you get?
You're not really modifying the WinRM service are you? Invoke-Command uses WinRM to execute the remote command. Test with a different service. I use Fax.
The main problem with the code that you have posted is that you are not testing the current status of the service. If it is already running, there is no need to issue a start for it.
Do it like this and display more information about what the script sees and performs. Note that the Fax service will not actually start. Replace Fax with the name of your service.
Invoke-Command -ComputerName test10 -ScriptBlock {
$SvcName = 'Fax'
$Report = $false
$Svc = get-service -Name $SvcName
"The {0} service is {1} and the start type is {2}" -f $SvcName, $Svc.Status, $Svc.StartType
if ($Svc.Status -eq "Stopped") {
"Starting the service"
Start-Service -Name $SvcName
Start-Sleep -Seconds 5
$Report = $true
}
if ($Svc.Status -ne "Automatic") {
"Setting to Automatic startup."
Set-Service -Name $SvcName -StartupType Automatic
$Report = $true
}
if ($Report) {
$Svc = get-service -Name $SvcName
"After changes, the {0} service is {1} and the start type is {2}" -f $SvcName, $Svc.Status, $Svc.StartType
}
}