Reputation: 133
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"}
Upvotes: 1
Views: 9006
Reputation: 21488
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:
-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.while
loops, until ( Test-NetConnection @tcnArgs ).TcpTestSucceeded
returns true. In other words, the loop code runs while the TCP test is failing.while
loop exits, output a string stating the TCP port is openUpvotes: 2