ARao
ARao

Reputation: 259

Can I use -ErrorVariable while using Out-String in Powershell

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

Answers (2)

tiberriver256
tiberriver256

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

Maximilian Burszley
Maximilian Burszley

Reputation: 19654

If your .list() method is throwing an exception you have two options:

  1. Set your $ErrorActionPreference variable to 'SilentlyContinue' or 'Ignore'

    $ErrorActionPreference = 'SilentlyContinue'
    
  2. 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

Related Questions