如何阻止Powershell命令“Get-NetFirewallRule”引发错误



我正在尝试使用Powershell确定防火墙规则是否存在。

如果规则不存在,我会收到一条丑陋的错误消息。如果它确实存在,一切都很好:)

如何检查规则是否存在,而不会出现任何丑陋的红色错误消息?

例如。

Import-Module NetSecurity
# Check if the firewall rule exists.
$existingRule = Get-NetFirewallRule -DisplayName $name

错误消息(当规则不存在时)...

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:projectsxwingSetup.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

请问有人知道如何安全地检查规则吗?

填充

cmdlet 的 -ErrorAction 参数

Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue

此时,您可以使用 $? 测试最后一个命令的结果。如果规则存在,这将返回$true

或者,您可以使用尝试/捕获块:

try {
  Get-NetFirewallRule -DisplayName blah -ErrorAction Stop
  Write-Host "Rule found"
}
  catch [Exception] {
  write-host $_.Exception.message
}

相关内容

最新更新