Powershell script to check if the service is running, if not, then run it

I created a small powershell script to check if the service is running. If it is not running, try starting it, then wait one minute and check again. Continue to repeat this process until the service starts successfully. I found that the loop does not behave as I expected, since it seems to me that I need to reassign the service variable inside the loop in order to get the updated state. Here is my code:

$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

if ($arrService.Status -ne 'Running'){
$ServiceStarted = $false}
Else{$ServiceStarted = $true}

while ($ServiceStarted -ne $true){
Start-Service $ServiceName
write-host $arrService.status
write-host 'Service started'
Start-Sleep -seconds 60
$arrService = Get-Service -Name $ServiceName #Why is this line needed?
if ($arrService.Status -eq 'Running'){
$ServiceStarted = $true}
}

If I run the code without the third last line (with a comment), I get the following output. I can check in the Windows Service Manager, and the service was clearly started after the first cycle. Why is this third last line needed?

enter image description here

Given this behavior, is there a better way to write this code?

+9
3

, , , : , , , , , :

.

$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

while ($arrService.Status -ne 'Running')
{

    Start-Service $ServiceName
    write-host $arrService.status
    write-host 'Service starting'
    Start-Sleep -seconds 60
    $arrService.Refresh()
    if ($arrService.Status -eq 'Running')
    {
        Write-Host 'Service is now Running'
    }

}
+17

$arrService = Get-Service -Name $ServiceName, $arrService.Status , . $arrService.Refresh() .

MSDN ~ ServiceController.Refresh()

.

+2
[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'

foreach($server in $servers)

{
    $srvc = Get-WmiObject -query "SELECT * FROM win32_service  WHERE   name LIKE '$service' " -computername $server  ;
    $res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;  
   $srvc.startservice() 
   $res
}
0

Source: https://habr.com/ru/post/1626374/


All Articles