1

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

  • PowerShell have false positive around Test-port: https://mikefrobbins.com/2016/04/28/be-mindful-of-object-types-when-writing-unit-tests-and-performing-operational-validation-in-powershell-with-pester/ – Francesco Mantovani Mar 10 '20 at 13:22

2 Answers2

3

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

doenoe
  • 211
  • 1
  • 13
0

Test-NetConnection will always return "False" for a localhost port. Use another tool (like canyouseeme.org) if you're checking to see if a port is open from a remote address.

Your Powershell looks fine, and you should see the rule if you look in the Windows Firewall rules GUI, but you can't test it the way you are attempting locally.

jski
  • 911
  • 1
  • 7
  • 20
  • Thank you @jski, but the goal is 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 – Francesco Mantovani Nov 14 '17 at 07:02