Problem
You want to open or close ports in the Windows Firewall.
Solution
To open or close ports in the Windows Firewall, use the LocalPolicy. CurrentProfile.GloballyOpenPorts collection of the HNetCfg.FwMgr COM object.
To add a port, create a HNetCfg.FWOpenPort COM object to represent the port, and then add it to the GloballyOpenPorts collection:
$PROTOCOL_TCP = 6
$firewall = NewObject com HNetCfg.FwMgr
$port = NewObject com HNetCfg.FWOpenPort
$port.Name = "Webserver at 8080"
$port.Port = 8080
$port.Protocol = $PROTOCOL_TCP
$firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add($port) To close a port, remove it from the GloballyOpenPorts collection:
$PROTOCOL_TCP = 6
$firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts.Remove(8080, $PROTOCOL_TCP)
Discussion
The HNetCfg.FwMgr COM object provides programmatic access to the Windows Firewall in Windows XP SP2 and later. The LocalPolicy.CurrentProfile property provides the majority of its functionality.
For more information about managing the Windows Firewall through its COM API, visit http://msdn.microsoft.com and search for “Using Windows Firewall API.” The documentation provides examples in VBScript but gives a useful overview of the functionality available.
If you are unfamiliar with the VBScriptspecific portions of the documentation, the Microsoft Script Center provides a useful guide to help you convert from VBScript to PowerShell. You can find that document at http://www.microsoft.com/technet/ scriptcenter/topics/winpsh/convert/default.mspx.