I'm trying to determine if a firewall rule exists or not, with Powershell.
If the rule does not exist, I get an ugly error message. If it does exist, all is good :)
How can I check if the rule exists without any ugly red error message occuring?
eg.
Import-Module NetSecurity
# Check if the firewall rule exists.
$existingRule = Get-NetFirewallRule -DisplayName $name
Error message (when the rule doesn't exist)...
Get-NetFirewallRule : No MSFT_NetFirewallRule objects found with property 'DisplayName' equal to 'Blah Blah Port 44444'. Verify the value of the property and retry. At C:\projects\xwing\Setup.ps1:67 char:21
+ $existingRule = Get-NetFirewallRule -DisplayName $name
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Blah Blah Port 44444:String) [Get-NetFirewallRule], CimJobException
+ FullyQualifiedErrorId : CmdletizationQuery_NotFound_DisplayName,Get-NetFirewallRule
Anyone know how to safely check for a rule, please?
Populate the -ErrorAction
parameter for the cmdlet
Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue
At this point you can test the result of the last command using $?
. If the rule exists, this will return $true
.
Alternatively, you can use a try / catch block:
try {
Get-NetFirewallRule -DisplayName blah -ErrorAction Stop
Write-Host "Rule found"
}
catch [Exception] {
write-host $_.Exception.message
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With