Question:
I’ve a powershell script that opens port 5555, but it defaults to profile = private, when I want it to be all (private, public, domain). How can I modify the script to achieve this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$port = New-Object -ComObject HNetCfg.FWOpenPort $port.Port = 5555 $port.Name = 'MyPort' $port.Enabled = $true $fwMgr = New-Object -ComObject HNetCfg.FwMgr $profile = $fwMgr.LocalPolicy.CurrentProfile $profile.GloballyOpenPorts.Add($port) $port = New-Object -ComObject HNetCfg.FWOpenPort $port.Port = 6521 $port.Name = 'ArkleSQL' $port.Enabled = $true $fwMgr = New-Object -ComObject HNetCfg.FwMgr $profile = $fwMgr.LocalPolicy.CurrentProfile $profile.GloballyOpenPorts.Add($port) |
Answer:
You can use FwPolicy2
and FWRule
to create a rule for all profiles:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$fwPolicy = New-Object -ComObject HNetCfg.FwPolicy2 $rule = New-Object -ComObject HNetCfg.FWRule $rule.Name = 'MyPort' $rule.Profiles = $NET_FW_PROFILE2_ALL $rule.Enabled = $true $rule.Action = $NET_FW_ACTION_ALLOW $rule.Direction = $NET_FW_RULE_DIR_IN $rule.Protocol = $NET_FW_IP_PROTOCOL_TCP $rule.LocalPorts = 5555 $fwPolicy.Rules.Add($rule) |
Here are the used constants:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$NET_FW_PROFILE2_DOMAIN = 1 $NET_FW_PROFILE2_PRIVATE = 2 $NET_FW_PROFILE2_PUBLIC = 4 $NET_FW_PROFILE2_ALL = 2147483647 $NET_FW_IP_PROTOCOL_TCP = 6 $NET_FW_IP_PROTOCOL_UDP = 17 $NET_FW_IP_PROTOCOL_ICMPv4 = 1 $NET_FW_IP_PROTOCOL_ICMPv6 = 58 $NET_FW_RULE_DIR_IN = 1 $NET_FW_RULE_DIR_OUT = 2 $NET_FW_ACTION_BLOCK = 0 $NET_FW_ACTION_ALLOW = 1 |
(Source: http://www.ohmancorp.com/files/RefWin-AdvFirewall-JCopyFWRules.txt)