Home > Blockchain >  How to use parameter splatting when piping to ForEach-Object?
How to use parameter splatting when piping to ForEach-Object?

Time:01-20

I am trying to use splatting at the pipeline, passing to ForEach-Object. Example code below:

$arr = @(
    @{
        Path = "C:\Folder1"
        Recurse = $true
    },
    @{
        Path = "C:\Folder2"
        Recurse = $true
    }
)

foreach ($obj in $arr) {
    Get-ChildItem @obj
}
# Working OK.

# Now use splatting with ForEach-Object:
$arr | ForEach-Object { Get-ChildItem @$_ }
# Not working.

I have also tried: Get-ChildItem @($_) which does not work.

The error message is:

Get-ChildItem : Cannot find path 'C:\System.Collections.Hashtable' because it does not exist.

CodePudding user response:

PowerShell's splatting, which enables passing arguments (parameter values) to commands via hashtables (named arguments) or, less commonly, arrays (positional arguments):

  • requires the hashtable / array to be stored in a variable (e.g. $foo), ahead of time.
  • must reference that variable with symbol @ instead of $ (e.g. @foo, not @$foo).

Therefore, use @_ in your case to splat via the automatic $_ variable:

$arr | ForEach-Object { Get-ChildItem @_ } # !! @_, not @$_

CodePudding user response:

You need to omit the $ from the variable name when splatting:

$arr | ForEach-Object { Get-ChildItem @_ }

CodePudding user response:

It's not elegant, but this seems to work:

$arr | ForEach-Object { $k = $_; get-childitem @k }

  • Related