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
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?

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