Opening up a port with powershell

port, powershell

Solution

Avoid COM if possible. You can use TcpListener to open a port:

$Listener = [System.Net.Sockets.TcpListener]9999;
$Listener.Start();
#wait, try connect from another PC etc.
$Listener.Stop();

If you happen to miss a `Stop` command during debugging - just close and re-open the application from where you opened the socket - hanging port should be cleared. In my case it was `PowerGUI script editor`.

Then use TcpClient to check it.

(new-object Net.Sockets.TcpClient).Connect($host, $port)

If you cannot connect, means the firewall is blocking it.

EDIT: To print a message when connection is received, you should be able to use this code (based on this article from MSDN):

#put this code in between Start and Stop calls.
while($true) 
{
    $client = $Listener.AcceptTcpClient();
    Write-Host "Connected!";
    $client.Close();
}

Problem

On `Machine A` I am running a port scanner. On `Machine B` I would like to open and close ports in an organized fashion. I am hoping to do all of this via powershell. I found THIS script to run on `Machine B` however when scanning the same port from `Machine A` it still says that it is closed. Do any of you know how I can successfully open a port on `Machine B`

Original source