I'm having some trouble with the 'Test-NetConnection' command in PowerShell. It works perfectly when I run it on its own, but after executing it inside a ForEach loop, it doesn't seem to work anymore. Even though the loop is closed, it's like it messes things up. I've shared two code snippets: the first one works ([link](https://pastebin.com/UJqxQnvS)), and the other one doesn't ([link](https://pastebin.com/23HWcnDJ)). Any insights on why this happens?
3 Answers
It's likely that 'Test-NetConnection' is working fine, but the $ProgressPreference setting might be causing it to not display output properly. You could try setting it to 'SilentlyContinue' to see if that helps. Check out this modified version of your code:
```powershell
$ProgressPreference = 'SilentlyContinue'
[string[]]$sites = 'yahoo.com'
ForEach ($Site in $Sites) {
[PSCustomObject][Ordered]@{
Site = $Site
HTTPS = (Test-NetConnection $Site -Port 443).TcpTestSucceeded
}
}
test-netconnection $sites[0] -port 443 | Out-Default
```
This way, your output should display correctly!
Have you tried adding a small delay with 'Start-Sleep' in your loop? It might help with how the commands are waiting for each other to process. Just a second or two could make a difference, letting everything settle before the next command executes.
I tried adding 'Start-Sleep', but it still didn’t produce any output.
This issue is actually related to how PowerShell displays output rather than a failure of 'Test-NetConnection' itself. When you output different objects in a pipeline, PowerShell tries to group them by the properties of the first object. If that first object doesn't have the expected properties, your subsequent commands might not display their output correctly. So, when your test command runs after the ForEach loop, it tries to pull formatting based on the first output, which leads to it showing as empty because 'Test-NetConnection' doesn't contain those properties. You can fix this with solutions like using 'Out-Host' or 'Format-Table' after your loop.
I don't get how the loop affects it, especially since a simple ping command works fine after the loop.