Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop the Powershell command `Get-NetFirewallRule` from throwing an error?

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?

like image 944
Pure.Krome Avatar asked Dec 08 '14 10:12

Pure.Krome


1 Answers

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
}
like image 116
arco444 Avatar answered Oct 19 '22 03:10

arco444