How can I stop Powershell `Get-NetFirewallRule` command from error?
I'm trying to determine if a firewall rule exists or not using Powershell.
If the rule doesn't exist, I get an ugly error message. If it exists, everything is fine :)
How can I check if a rule exists without some ugly red error message?
eg.
Import-Module NetSecurity
# Check if the firewall rule exists.
$existingRule = Get-NetFirewallRule -DisplayName $name
Error message (when the rule does not 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
Does anyone know how to safely check the rule please?
source to share
Configure the parameter -ErrorAction
for the cmdlet
Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue
At this point, you can check 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
}
source to share