Which Powershell Function could check whether a certain port is in LISTENING state on localhost?
If you're using PowerShell v3.0+ on Windows 8/Server 2012 or later, then instead of trying to connect to the port to determine the state, you can simply use Get-NetTCPConnection
:
Get-NetTCPConnection -State Listen
To me this is more accurate as it's reading the status of the port on the computer. Using a connection to test can make it seem like it's not "LISTENING" when it is, if a firewall or alike gets in the way or something.
First create and store the connection:
$connection = (New-Object Net.Sockets.TcpClient)
$connection.Connect("127.0.0.1",10389)
Then check if it's connected
if ($connection.Connected) {
"We're connected"
}
Or as suggested by Colyn1337
Try {
$connection = (New-Object Net.Sockets.TcpClient)
$connection.Connect("127.0.0.1",10389)
"Connected"
}
Catch {
"Can't Connect"
}