I was setting up a monitoring script that would ping IPs and send an email when a packet fails. I decided to use Test-Connection
. Below is a sample code:
Code1
$IPList = @("192.168.0.1","172.217.161.15")
Test-Connection -ComputerName $IPList -BufferSize 4 -Count 1 -AsJob -ErrorAction Stop
Get-Job | Wait-Job | Receive-Job
So the result I get is:
Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
BLR-AA200906 172.217.161.15 4 55
BLR-AA200906 192.168.0.1 4
The 192 series IP is supposed to throw an error. You can see that the Time(ms)
column is empty.
Code2
$IPList = @("192.168.0.1","172.217.161.15")
foreach ($IP in $IPList)
{
Start-job -ScriptBlock {Test-Connection -ComputerName $Args[0] -BufferSize 4 -Count 1 -ErrorAction Stop} -ArgumentList $IP
}
Get-Job | Wait-Job | Receive-Job
If I do this, it will throw an error that I can easily catch
Testing connection to computer '192.168.0.1' failed: Error due to lack of resources
+ CategoryInfo : ResourceUnavailable: (192.168.0.1:String) [Test-Connection], PingException
+ FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand
+ PSComputerName : localhost
The Question
This brings me to my question. How can I receive/catch error messages thrown in Code1? The difference is I am using -AsJob
which is much more efficient than spinning up a job in a foreach
loop.
PS Version is 5.1