Skip to content

Instantly share code, notes, and snippets.

@jaapbrasser
Forked from Stephanevg/Get-NetshFireWallRule
Created January 17, 2017 09:13
Show Gist options
  • Save jaapbrasser/e832ae6cb0db76eb6671b3c8ac6bbd21 to your computer and use it in GitHub Desktop.
Save jaapbrasser/e832ae6cb0db76eb6671b3c8ac6bbd21 to your computer and use it in GitHub Desktop.
Get the current firewall rules. This function is a wrapper around NETSH. It has been written to address the lack of cmdlet on Windows 2008R2 and previous versions. It should be used ONLY for systems prior to 2012.
Function Get-NetshFireWallrule {
Param(
[String]$RuleName
)
if ($RuleName){
$Rules = netsh advfirewall firewall show rule name="$ruleName"
}else{
$Rules = netsh advfirewall firewall show rule name="all"
}
$return = @()
$HAsh = [Ordered]@{}
foreach ($Rule in $Rules){
if ($Rule -match '^Rule Name:\s+(?<RuleName>.+$)'){
$Hash.RuleName = $Matches.RuleName
}Else{
if ($Rule -notmatch "----------------------------------------------------------------------"){
switch -Regex ($Rule){
'^Rule Name:\s+(?<RuleName>.*$)'{$Hash.RuleName = $MAtches.RuleName;Break}
'^Enabled:\s+(?<Enabled>.*$)'{$Hash.Enabled = $MAtches.Enabled;Break}
'^Direction:\s+(?<Direction>.*$)'{$Hash.Direction = $MAtches.Direction;Break}
'^Profiles:\s+(?<Profiles>.*$)'{$Hash.Profiles = $MAtches.Profiles;Break}
'^Grouping:\s+(?<Grouping>.*$)'{$Hash.Grouping = $MAtches.Grouping;Break}
'^LocalIP:\s+(?<LocalIP>.*$)'{$Hash.LocalIP = $MAtches.LocalIP;Break}
'^RemoteIP:\s+(?<RemoteIP>.*$)'{$Hash.RemoteIP = $MAtches.RemoteIP;Break}
'^Protocol:\s+(?<Protocol>.*$)'{$Hash.Protocol = $MAtches.Protocol;Break}
'^LocalPort:\s+(?<LocalPort>.*$)'{$Hash.LocalPort = $MAtches.LocalPort;Break}
'^RemotePort:\s+(?<RemotePort>.*$)'{$Hash.RemotePort = $MAtches.RemotePort;Break}
'^Edge traversal:\s+(?<Edge_traversal>.*$)'{$Hash.Edge_traversal = $MAtches.Edge_traversal;$obj = New-Object psobject -Property $Hash;$return += $obj;Break}
default {Break}
}
}
}
}
return $return
}
$AllRules = Get-NetshFireWallrule
$AllRules
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment