Pur*_*ome 6 powershell firewall
我试图用Powershell确定防火墙规则是否存在.
如果该规则不存在,我得到一个丑陋的错误消息.如果确实存在,一切都很好:)
如何检查规则是否存在而没有出现任何丑陋的红色错误消息?
例如.
Import-Module NetSecurity
# Check if the firewall rule exists.
$existingRule = Get-NetFirewallRule -DisplayName $name
Run Code Online (Sandbox Code Playgroud)
错误消息(当规则不存在时)...
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
Run Code Online (Sandbox Code Playgroud)
有人知道如何安全地检查规则吗?
填充-ErrorAction
cmdlet 的参数
Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue
此时,您可以使用测试最后一个命令的结果$?
.如果规则存在,则返回$true
.
或者,您可以使用try/catch块:
try {
Get-NetFirewallRule -DisplayName blah -ErrorAction Stop
Write-Host "Rule found"
}
catch [Exception] {
write-host $_.Exception.message
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2035 次 |
最近记录: |