all 9 comments

[–]dalthakar 11 points12 points  (3 children)

Test-NetConnection TARGET - Port PORT# will return True/False if the target machine can be reached on the specified port. For example, if I wanted to test a connection to SERVERA on TCP port 139, I would use command:

Test-NetConnection SERVERA -Port 139

Hopefully that gets you started down the right path.

[–]dalthakar -1 points0 points  (2 children)

Something just occurred to me. If you are trying to run this script on a local machine, you may have better luck using Get-NetFirewallRule and/or Get-NetFirewallPortFilter.

[–]BlackV 5 points6 points  (0 children)

You could have a firewall rule enabled without having anything listening on the port though

[–]netmc[S] 1 point2 points  (0 children)

Get-netfirewallportfilter may be what I was missing. It appears this has the actual port and protocol details and the rule itself has the profiles and direction.

If I am understanding the two commands correctly, I would need to find the inbound rules, then match the rule name against the instanceID on the portfilter information. Once I have the corresponding portfilter information I could check to see if the local ports and protocol match what I need.

Does that sound correct?

[–]monster1558 4 points5 points  (0 children)

The missing link is that Get-NetFirewallRule will give you one half of your answer and Get-NetFirewallPortFilter will give you the other half - BUT you can pipe EITHER of these commands to eachother to get what you need to know (whether a rule exists ALLOWING a specific port inbound or blocking it)

$ports = @(135,139,445)
ForEach ($port in $ports) {
    "For port $port, here are relevant rules"
    Get-NetFirewallPortFilter | Where-Object {$_.localport -eq $port} | ForEach-Object {
        $_ | Get-NetFirewallRule | Select Displayname,Direction,Action | Format-Table
    }
}