Seems your $PolicyObjects
is a list of your group policy displaynames. I'd tighten up your code in one of the following manners.
$PolicyObjects | ForEach-Object {
$GPO = Open-NetGPO -PolicyStore "contoso.com$_"
foreach($rule in Get-NetFirewallRule -GPOSession $GPO)
{
$portfilter = $rule | Get-NetFirewallPortFilter
$addressfilter = $rule | Get-NetFirewallAddressFilter
[PSCustomObject]@{
GPOName = $_
RuleName = $rule.name
DisplayName = $rule.displayname
DisplayGroup = $rule.displaygroup
Protocol = $portfilter.Protocol
LocalPort = $portfilter.LocalPort
RemotePort = $portfilter.RemotePort
RemoteAddress = $addressfilter.RemoteAddress
Enabled = $rule.enabled
Profile = $rule.profile
Direction = $rule.direction
Action = $rule.action
}
}
} | Export-CSV $env:tempgpos.csv -Force
Start-Process notepad $env:tempgpos.csv
or
$csvdata = foreach($policy in $PolicyObjects)
{
$GPO = Open-NetGPO -PolicyStore "contoso.com$policy"
foreach($rule in Get-NetFirewallRule -GPOSession $GPO)
{
$portfilter = $rule | Get-NetFirewallPortFilter
$addressfilter = $rule | Get-NetFirewallAddressFilter
[PSCustomObject]@{
GPOName = $policy
RuleName = $rule.name
DisplayName = $rule.displayname
DisplayGroup = $rule.displaygroup
Protocol = $portfilter.Protocol
LocalPort = $portfilter.LocalPort
RemotePort = $portfilter.RemotePort
RemoteAddress = $addressfilter.RemoteAddress
Enabled = $rule.enabled
Profile = $rule.profile
Direction = $rule.direction
Action = $rule.action
}
}
}
$csvdata | Export-CSV $env:tempgpos.csv -Force
Start-Process notepad $env:tempgpos.csv
In the first one we change the outer loop to a Foreach-Object
to take advantage of the pipeline and piping straight to Export-Csv
.
In the second we capture all the output then export.
In both we limit the execution time by limiting the opening/writing to file to one time, limit the portfilter calls to one per rule instead of 3, and we use the [PSCustomObject]
type accelerator to construct our final object instead of piping to Select-Object
with calculated expressions. Both should achieve your desired result if I understood correctly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…