PowerShell: how open a Windows Firewall port

portpowershellwindows-firewall

I need to open a port on Windows Firewall with PowerShell, so I do

netsh advfirewall firewall add rule name = "Open port 4443 test" dir=in action=allow protocol=TCP localport=4443

and then

Test-NetConnection -Port 4443 -ComputerName localhost

to check if the port is open but it's still closed.

So I try with another command:

New-NetFirewallRule -DisplayName "Allow inbound TCP port 4443" -Direction inbound -LocalPort 4443 -Protocol TCP -Action Allow

but still no joy.

So the question is: how do I open port 4443 through PowerShell?

EDIT: The rule is created into Windows Firewall but I need a command that returns me a True/False check response

Best Answer

To answer your question in the comments: to make a PowerShell script that returns you if the port is open or not so I need to have a positive/negative response from PowerShell

Maybe this can help you out, use the System.Net.Sockets.TcpClient class to test if a port is open or closed. Look at the following code:

$ErrorActionPreference = "silentlycontinue"

$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("localhost","1234")
$tcp.Connected 

$tcp.connected will return true if the connection succeeded. False if it wont succeed. The $ErrorActionPreference = "silentlycontinue" variable will suppress error messages.

Example:

enter image description here