Reputation: 465
I'm trying to process firewall rules in a powershell script - here is the line I'm using:
$currentRules = get-netfirewallRule -CimSession computer4 -direction Inbound
So this works fine if it returns any rules, returns a collection of some sort which are stored in $currentRules. All good.
the problem arises if get-netfirewallrule doesn't find any matches - I get a helpful
get-netfirewallRule : computer4: No MSFT_NetFirewallRule objects found with property 'Direction' equal to 'Inbound'. Verify the value of the property and retry.
At line:1 char:1
+ get-netfirewallRule -CimSession computer4 -direction Inbound | ou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Inbound:Direction) [Get-NetFirewallRule], CimJobException
+ FullyQualifiedErrorId : CmdletizationQuery_NotFound_Direction,Get-NetFirewallRule
+ PSComputerName : computer4
splatted in the middle of my output. I've tried the usual > $null and | out-null, but still the output ends up on my screen. Any ideas how I can stop it displaying this 'useful' message?
thanks,
Jim
Upvotes: 0
Views: 601
Reputation: 3168
Using the Try/Catch construct allows you to trap errors and process them preventing unwanted error messages from appearing in your output.
$GNFArgs = @{CimSession = "computer4"
Direction = "Inbound"
ErrorAction = "Stop"
}
Try {
$currentRules = get-netfirewallRule @GNFArgs
}
Catch {
#Process error here
}
HTH
Upvotes: 0
Reputation: 61208
Peter Schneiders helpful answer is correct, although you would normally use that when you need the erroraction set for more cmdlets.
If you only want to suppress the error output for this one command, you can also specify parameter -ErrorAction SilentlyContinue
to it straight away like:
$currentRules = Get-NetFirewallRule -CimSession computer4 -Direction Inbound -ErrorAction SilentlyContinue
There is also the -ErrorVariable
parameter with wich you can have the code capture any exception inside a variable of your own and inspect that later:
$currentRules = Get-NetFirewallRule -CimSession computer4 -Direction Inbound -ErrorAction SilentlyContinue -ErrorVariable MyErrorVar
# display the error if any
$MyErrorVar
Sometimes, a cmdlet outputs an exception eventhough the ErrorAction is set to 'SilentlyContinue'. In these cases you can also use the a try{}..catch{}
block.
You then need to set the ErrorAction to 'Stop' so also non-terminating errors are directed to the catch block:
try {
$currentRules = Get-NetFirewallRule -CimSession computer4 -Direction Inbound -ErrorAction Stop
}
catch {
# write custom message on screen or write to log file or..
Write-Warning "Failed to get Firewall rules.."
}
Upvotes: 2
Reputation: 2939
You can set the $ErrorActionPreference variable to "SilentlyContinue"
$eap = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
1/0
$ErrorActionPreference = $eap
Upvotes: 1