I have a script that is currently monitoring a couple of windows services on different VMs. If the service is stopped, it will attempt to start the service.
I have added a $LoopCounter to stop the script it it loops to many time as to not fall into an infinite loop if the service cannot be started for what ever reason.
This is all inside a Invoke-Command that runs some code on the remote VMs. I have used Exit to stop the script running but it does not seem to be in the right scope of things and it stops the Invoke-Command but not the whole script.
Script:
Invoke-Command -ComputerName VM1, VM2, VM3 -Credential $Cred -ArgumentList $ServiceList -ScriptBlock {
Foreach ($Service in $Using:ServiceList) {
$C = [System.Net.Dns]::GetHostName()
$S = Get-Service -Name $Service
while ($S.Status -ne 'Running') {
# Code...
$LoopCounter++
If($LoopCounter -gt 2) {
Exit
}
}
}
}
Return MustExitwhen the loopcounter condition is met. Then during your main loop, check for that return and exit accordingly.