How to open a firewall port in Windows using Power Shell

I would like to know how to open a firewall port in Windows by using Power Shell.Could anyone write a script for opening a firewall port.I saw a similar post on https://stackoverflow.com/questions/24760821/changing-windows-firewall-rules-with-powershell-open-close-a-specific-port but couldn't understand how to do it.

I would just want to open a port:8983 in windows because when I execute the application(stack dump) it says pysolr.SolrError: Failed to connect to server at 'http://localhost:8983/solr/stackdump/admin/ping', are you sure that URL is correct?.Atlast it says:No connection could be made because the target machine actively refused it.


Solution 1:

You can refer to the guide here.

The command to open port 80 is:

netsh advfirewall firewall add rule name="Open Port 80" dir=in action=allow protocol=TCP localport=80

You need to specify:

  • name for the rule
  • direction
  • whether to allow the connection
  • protocol used
  • port number

You can use this command from the Powershell level.

If you absolutely must use Powershell, you can use something like the script below(for the port 80 as well):

#==============================================================
# Creates a rule to open an incomming port in the firewall.
#==============================================================

#$numberAsString = read-host "type an port number"
#$mynumber = [int]$numberAsString


$port1 = New-Object -ComObject HNetCfg.FWOpenPort

$port1.Port = 80

$port1.Name = 'MyTestPort' # name of Port

$port1.Enabled = $true

$fwMgr = New-Object -ComObject HNetCfg.FwMgr

$profiledomain=$fwMgr.LocalPolicy.GetProfileByType(0)

$profiledomain.GloballyOpenPorts.Add($port1)

Taken from here.