LightningWar
LightningWar

Reputation: 975

How to use parameter splatting when piping to ForEach-Object?

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.

Upvotes: 2

Views: 552

Answers (2)

mklement0
mklement0

Reputation: 437408

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 @$_

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

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

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

Upvotes: 2

Related Questions