'Powershell looping Test-NetConnection
I'm a bit new to Powershell scripting and I'm trying to create a simple loop with the Test-NetConnection tool, but I don't know how to do this. This is what I have:
param(
[string]$tcpserveraddress,
[string]$tcpport
)
if (Test-NetConnection -ComputerName $tcpserveraddress -Port $tcpport -InformationLevel Quiet -WarningAction SilentlyContinue) {"Port $tcpport is open" }
else {"Port $tcpport is closed"}
If the tcpport is not open, I would like the script to loop and issue the text "Port $tcpport is closed" every 10 seconds, until it is open. When tcppport is open, it should display the "Port $tcpport is closed" text and terminate. It must be something very simple, but I somehow can't find it through Google. Thank you very much for your help in advance!
Kind regards, Eric
Solution 1:[1]
We can use a while loop to achieve this with a few modifications to your existing code:
param(
[string]$tcpserveraddress,
[string]$tcpport
)
$tcnArgs = @{
ComputerName = $tcpserveraddress
Port = $tcpport
WarningAction = 'SilentlyContinue'
}
while( !( Test-NetConnection @tcnArgs ).TcpTestSucceeded ) {
"Port $tcpport is closed"
Start-Sleep -Seconds 60
}
"Port $tcpport is open"
Since you indicated you are new to PowerShell, here's a breakdown of how this works:
- For the sake of readability, I have use argument splatting to define and pass the cmdlet parameters as a hashmap. Here are some additional answers that explain splatting in more detail, for those interested.
- No longer use
-InformationLevel Quiet. In a script we generally want the detailed object as it has more information on it, and we can operate off of its properties. - The
whileloops, until( Test-NetConnection @tcnArgs ).TcpTestSucceededreturns true. In other words, the loop code runs while the TCP test is failing. - Sleep in the loop, no need to check constantly.
- Once the
whileloop exits, output a string stating the TCP port is open
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
