Reputation: 259
I'm trying to capture the output of a command into output variable in Powershell. The output of the command is in table format which is why I'm using Out-String. Now I need to suppress the error messages which is why I use an error variable to store the error messages. I tried the following things but none of them suppress my error and error gets displayed on screen.
$output = $esxcli.network.firewall.ruleset.allowedip.list() | Out-String -ErrorVariable myErr
$output = $esxcli.network.firewall.ruleset.allowedip.list() -ErrorVariable myErr | Out-String
$output = $esxcli.network.firewall.ruleset.allowedip.list() | Out-String 2>&1
$output = $esxcli.network.firewall.ruleset.allowedip.list() 2>&1 | Out-String
Is there a way where I can suppress the errors while using Out-String in a simple way (nothing like try-catch)?
Upvotes: 2
Views: 680
Reputation: 539
To add a bit more detail to your original question about -ErrrorVariable
. -ErrorVariable
is a common parameter which you get by default when adding the CmdletBinding attribute to the beginning of a function.
The .list()
is a .Net method not a PowerShell function and thus -ErrorVariable
does not work with it. You can however write a short function to wrap the .Net method in a small PowerShell function if you would like to use it a lot and would like to leverage some of PowerShell's awesomeness with that method.
Example:
function Get-ESXAllowedIPList {
[CmdletBinding()]
param($esxcli)
return $esxcli.network.firewall.ruleset.allowedip.list()
}
You can then use it like this:
Get-ESXAllowedIPList -ErrorAction SilentlyContinue -ErrorVariable ESXAllowedIPListErrors | Out-String
Upvotes: 2
Reputation: 19654
If your .list()
method is throwing an exception you have two options:
Set your $ErrorActionPreference
variable to 'SilentlyContinue'
or 'Ignore'
$ErrorActionPreference = 'SilentlyContinue'
Wrap your method call in a try/catch block
try
{
$output = $esxcli.network.firewall.ruleset.allowedip.list() | Out-String
}
catch
{
"Error thrown! $PSItem"
}
Do note if your method call is throwing a terminating error, you do not have a workaround.
Upvotes: 3