r/PowerShell • • Apr 05 '19

PowerShell tricks: Splatting

https://blog.destruktive.one/powershell-tricks-splatting/
150 Upvotes

58 comments sorted by

View all comments

Show parent comments

4

u/TheIncorrigible1 Apr 05 '19

How it passes the arguments. $x will convert your array using ToString and doesn't pass them properly.

4

u/ka-splam Apr 05 '19

$x will convert your array using ToString and doesn't pass them properly.

Clearly not, as shown by my example use of $x working instead of saying 'system.object[]' is not recognized as an internal or external command

4

u/TheIncorrigible1 Apr 05 '19

You missed the point. See: about_Parsing.

Also:

"$('echo', 'b', 'c')"

Is more akin to what is happening here. Calling ToString literally on the array calls the wrong overloaded method.

3

u/ka-splam Apr 05 '19

You missed the point.

Duh, yes, that's why I'm asking about it.

"$('echo', 'b', 'c')" Is more akin to what is happening here.

if it were exactly that, changing $OFS would change the behaviour, which it doesn't, e.g.:

PS C:\> $x = @('echo', 'b', 'c')
PS C:\> "$x"
echo b c
PS C:\> $OFS=','
PS C:\> "$x"
echo,b,c
PS C:\> cmd /c $x
b c
PS C:\> cmd /c @x
b c

akin to it, how?

See: about_Parsing.

I'm not seeing anything there which explains the difference, or in about_Splatting, except saying that you can do it.

Show an example where it behaves differently?

1

u/ka-splam Apr 08 '19

Turns out it behaves differently for cmdlets (but possible not native commands(?)):

PS C:\> function test { $args -join '-' }
PS C:\> $x = @('echo', 'b', 'c')
PS C:\> test $x
System.Object[]
PS C:\> test @x
echo-b-c

Like Python's somefunc(*var) which I've wanted before, so woooo

1

u/TheIncorrigible1 Apr 08 '19

Yes, when used with a cmdlet, it sees that as a single argument