I see two ways we can do it, the simplest way is creating a job and periodically receive it to see if the status changed:
$block = {
while ($true) {
grpcurl -d '{ \"service1\": \"name1\" }' -H "authorization: key key" host1:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service2\": \"name2\" }' -H "authorization: key key" host2:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service3\": \"name3\" }' -H "authorization: key key" host3:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service4\": \"name4\" }' -H "authorization: key key" host4:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service5\": \"name5\" }' -H "authorization: key key" host5:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service6\": \"name6\" }' -H "authorization: key key" host6:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service7\": \"name7\" }' -H "authorization: key key" host7:port grpc.health.v1.Health/Check
start-sleep 2
}
}
$job = Start-Job -Name 'gRPCMon' -ScriptBlock $block
while ($true) {
$result = Receive-Job -Id $job.Id
if (($result | ConvertFrom-Json).status -ne 'SERVING') {
## Send-MailMessage here
}
}
Or, in a more elegant way, we can run your code in a runspace and raise an event every time the condition is met.
Then, we subscribe to that event:
$block = {
while ($true) {
grpcurl -d '{ \"service1\": \"name1\" }' -H "authorization: key key" host1:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service2\": \"name2\" }' -H "authorization: key key" host2:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service3\": \"name3\" }' -H "authorization: key key" host3:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service4\": \"name4\" }' -H "authorization: key key" host4:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service5\": \"name5\" }' -H "authorization: key key" host5:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service6\": \"name6\" }' -H "authorization: key key" host6:port grpc.health.v1.Health/Check>> grpcurl -d '{ \"service7\": \"name7\" }' -H "authorization: key key" host7:port grpc.health.v1.Health/Check
start-sleep 2
if (($output | ConvertFrom-Json).status -ne 'SERVING') {
$x.Host.Runspace.Events.GenerateEvent('StatusEvent', $null, $null, "Status Event")
}
}
}
$Global:x = [hashtable]::Synchronized(@{})
$x.Host = $Host
$runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()
$runspace.Open()
$runspace.SessionStateProxy.SetVariable("x",$x)
$powershell = [System.Management.Automation.PowerShell]::Create()
$powershell.Runspace = $runspace
$powershell.AddScript($block)
$IActionResult = $powershell.BeginInvoke()
Register-EngineEvent -SourceIdentifier 'StatusEvent' -Action {
## Send-MailMessage here
}
Let me know if that did the trick.