Powershell script to check if service is started, if not then start it
<p>I have built a small powershell script to check if a service is started.  If it is not started, try to start it then wait one minute and check again.  Keep repeating this process until the service start successfully.  I have found the loop does not behave the way I expected in that I seem to have to re-assign the service variable within the loop in order to get the updated status.  Here is my code:</p>

<pre><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}
}
</code></pre>

<p>If I run the code without the third last line (the one with the comment), I get the following output.  I can check in the Windows service manager and the service was clearly started after the first loop.  Why is that third last line required?</p>

<p><a href="https://i.stack.imgur.com/pX8uK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pX8uK.png" alt="enter image description here"></a></p>

<p>Given this behavior, is there a better way to write this code?</p>

<p>Thank you</p>