I am trying to create multiple firewall rules, but I don't want to create a duplicate rule if it already exists.
Currently, my script will create the first rule, but then as it goes through the loop, it will always say that there's already a duplicate rule, so it will stop. Is there a way to apply all the rules in my array?
$c = "wsbxlcfe101"
$fwNames = @("ECMP - OutSystems LifeTime", "ECMP - OutSystems Deployment Controller")
foreach($name in $fwNames){
$session = New-PSSession -ComputerName $c
$ifFirewallExists = Invoke-Command -Session $session -ScriptBlock {
Get-NetFirewallRule -Direction Inbound -ErrorAction SilentlyContinue | where DisplayName -Match "ECMP" | select DisplayName, Enabled, Direction, Action
}
if ($ifFirewallExists.DisplayName){
Write-Host "firewall rules already created." -ForegroundColor Red
}
else {
New-NetFirewallRule -DisplayName $name -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort "80","443"
Write-Host "Rules created." -ForegroundColor Green
}
Remove-PSSession -Session $session
}
EDIT*****
Here's the updated code, looks to be working
try {
$c = "wsbxlcfe101"
$session = New-PSSession -ComputerName $c
Invoke-Command -ScriptBlock {
$fwNames = @("ECMP - OutSystems LifeTime", "ECMP - OutSystems Deployment Controller")
foreach($name in $fwNames){
$FirewallRules = Get-NetFirewallRule -Direction Inbound -ErrorAction SilentlyContinue
if ($FirewallRules.DisplayName -eq $name){
Write-Host "firewall rules already created." -ForegroundColor Red
}
else {
New-NetFirewallRule -DisplayName $name -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort "80","443"
Write-Host "$name rule created." -ForegroundColor Green
}
}
} -Session $session
}
catch {
Write-Host $_ -ForegroundColor Red
}
finally {
Get-PSSession | Remove-PSSession
}