powershellget-childitemparameter-splatting

Powershell splatting: pass ErrorAction = Ignore in hash table


Here's a script to list directories / files passed on the command line -- recursively or not:

param( [switch] $r )
@gci_args = @{
  Recurse = $r
  ErrorAction = Ignore
}
$args | gci @gci_args 

Now this does not work because Ignore is interpreted as a literal. What's the canonical way to pass an ErrorAction?

I see that both "Ignore" and (in PS7) { Ignore } work as values, but neither seems to make a difference for my use case (bad file name created under Linux, which stops PS5 regardless of the ErrorAction, but does not bother PS7 at all). So I'm not even sure the parameter has any effect.


Solution

  • I think the best way is to use native type.

    $ErrorActionPreference.GetType().FullName # System.Management.Automation.ActionPreference
    

    So, use

    $gci_args = @{   
      Recurse = $r
      ErrorAction = [System.Management.Automation.ActionPreference]::Ignore
    }