I'm trying to create a simple network scanner using PowerShell and I want it to run multiple "pings (or in this case test-connection)" in parallel.
Start-Job seems to be the best way to accomplish this multi-threading scenario.
Here is a simplified example of what i'm trying to do.
$list=@("192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4")
ForEach ($item In $list) {
Start-Job -ScriptBlock {
if (Test-Connection $item -Quiet -Count 1) {
Add-Content -value "$item found" -Path C:\logs\test.txt
}
}
}
This however does nothing. If I remove the Start-Job part it does work, but loses its multiprocessing. If I remove the if statement the writing to file part works.
So the issue seems to be when using an if statement in a scriptblock within a job.
There must be something about the start-job command i'm missing. Or is there any better way to create this kind of script?