0

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
            }
        }
    }
}
1
  • If you loop through your computer name list, then you can do something like Return MustExit when the loopcounter condition is met. Then during your main loop, check for that return and exit accordingly. Commented Sep 13, 2019 at 12:58

1 Answer 1

1

You could have the scriptblock return a value and check for that. The example below has the returned value 1 if the script should exit as a whole:

$result = 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) {
                return 1   # return a value other than 0 to the calling script
                Exit       # exit the scriptblock
            }
        }
    }
}
# check the returned value from Invoke-Command
# if it is not 0 (in this example), exit the whole script
if ($result) { exit }

Hope that helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.