Reputation: 2417
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
}
}
}
}
Upvotes: 0
Views: 732
Reputation: 61013
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
Upvotes: 1