r/PowerShell • • Apr 05 '19

PowerShell tricks: Splatting

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

58 comments sorted by

27

u/si1ic0n_gh0st Apr 05 '19

Splatting doesn't sound all that cool, until you realize that you can use it to vary what arguments you pass to a cmdlet/program. To build on Destruktive's example, there might be times where you don't want to set OpenPorts or maybe sometimes you'll need to also add PublicIpAddressName.

​

With splatting you can dynamically build your arguments, then hand them off to whatever you are trying to execute. Really cleans up your code.

5

u/destruktive Apr 05 '19

It can really help when doing automation based on conditions and I might actually write an example of that in the future.

I wrote this just because I wanted to get people to write cleaner code ;)

1

u/xenaprincesswarlord Apr 06 '19

Can you please eli5?im learning to code now I never even heard of splat

1

u/destruktive Apr 06 '19

Have an exam in a couple of hours but I can write something later today πŸ€“

1

u/xenaprincesswarlord Apr 06 '19

Today, tomorrow it’s fine!

4

u/lolinux Apr 06 '19

Splatting is basically creating a hashtable where you will hold all of the parameters that you will use for a future command. If you read the original post, you might have noticed that the keys of the hashtable are the names of the arguments, and the values of the hashtable are the values that will be passed to the cmdlet. The only caveat is that when you actually call the cmdlet, you will have to prepend an @ not just an $, like with normal variables.

1

u/xenaprincesswarlord Apr 06 '19

I see. Seems smart actually!

3

u/si1ic0n_gh0st Apr 05 '19

I use it quite a bit in a script where I'm passing arguments off to a wrapper I use for WinSCP. There are all sorts of different arguments you might need to pass based on protocol or authentication requirements (SSH key auth for instance). Splatting makes this fairly easy to accomplish.

2

u/[deleted] Apr 06 '19

I don’t think the example in the link showed how that conditional parameter setting would be done, could you post a basic example?

2

u/destruktive Apr 06 '19

Will absolutely do an example of this later on, there will be a follow up :)

1

u/[deleted] Apr 06 '19

Thanks, it’s much appreciated!

3

u/sir_sandwiches_a_lot Apr 05 '19

Excellent point- this is my main usage for it too.

2

u/BlackV Apr 06 '19

ditto, that and prettiness/tidyness

2

u/etcetica Apr 06 '19

splatting: really cleans up your code

ironic, as it sounds like a weird sex act

3

u/TapTapLift Apr 06 '19

Good read, thank you!

2

u/destruktive Apr 06 '19

Thank you, and you're welcome 😊

2

u/neotrin2000 Apr 06 '19

My question is, what on earth was someone thinking when they named this technique "splatting"

1

u/destruktive Apr 06 '19

I have no idea... When I first read the name, I wasn't even sure what to expect πŸ™„

4

u/Ta11ow Apr 06 '19

The name predates PowerShell, actually. Similar constructs are available in quite a few languages, and it probably seemed better to name it after its kindred constructs rather than give it a shiny new buzzword that wouldn't be recognised by other programmers. :)

2

u/Lee_Dailey [grin] Apr 06 '19

howdy neotrin2000,

in addition to what Ta11ow mentioned - reusing other lingo terminology - i recall that one old, ancient nickname for an @ is splat. [grin]

/lee bee gee zer [grin]

take care,
lee

29

u/a-rich Apr 05 '19

Taking it one step further, you can pass multiple splats.

Say, for instance you're using Send-MailMessage and have some common parameters, like smtpserver, from and port, you can put them all into $CommonSplat.

Then you can make a separate splat for more dynamic parameters, like To, Subject and Body as $DynamicSplat and pass both.

You can build that dynamic splat based on certain conditionals and use one send-mailmessage to take care of the sending all nice and neat like.

Send-MailMessage @CommonSplat @DynamicSplat

​

And since the splat is just a hash table, you can build it and customize it however you like.

$Splat.add()

$Splat.remove(

$Splat[key] = @("An array", "of values", "if the parameter", "supports it")

​

That article is ok as a very brief into to splatting, but theres definitely more to explore!

4

u/[deleted] Apr 05 '19

I feel like an idiot for not knowing this. I usually write if statements to dynamically build my splat didn't realize you use multiple ones, but I feel like I should have.

2

u/panzerbjrn Apr 06 '19

I've used splatting for ages, but never realised you could use multiple splats - __- Thanks πŸ‘πŸ‘πŸ‘ŒπŸ‘Œ

3

u/motsanciens Apr 05 '19

You da real MVP.

I had to play around to concrete the idea in my head...

function test-splat {

    param(
        [int]$one,
        [int]$two,
        [int]$three,
        [int]$four,
        [int]$five,
        [int]$six,
        [int]$seven
    )

    $MyInvocation.BoundParameters
}

$splat1 = @{
    one = 9
    two = 10
    three = 55
}

$splat2 = @{
    seven = 11
}

$splat3 = @{
    four = 44
    five = 0
    six = 100
}

test-splat @splat1 @splat2 @splat3

6

u/p0rkjello Apr 06 '19

You can also append the splat based on your input parameters. I run into it often when Credentials are required.

function Get-CimSometing {
    [CmdletBinding()]
    param(
        [string[]]    
        $ComputerName = $env:COMPUTERNAME,

        [string]
        $ClassName = 'Win32_Process',

        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = [System.Management.Automation.PSCredential]::Empty,
    )

    foreach ($Computer in $ComputerName) {
        $Splat = @{
            ComputerName = $Computer
            ClassName = $ClassName
        }

        if ($PSBoundParameters.ContainsKey('Credential') {
            $Splat.Credential = $Credential 
        }
        Get-CimInstance @Splat
    }
}

1

u/joerod Apr 06 '19

My favorite use case πŸ™‚

3

u/joerod Apr 06 '19

Splatting is so useful, especially when you want to set parameters logically.

9

u/Lee_Dailey [grin] Apr 05 '19

howdy destruktive,

"splatting - homely name, lovely effect" [grin]

i dearly love the readability. plus, it's easy to comment, edit, change, disable, add, or remove stuff right in the splat.

take care,
lee

2

u/Lagrik Apr 05 '19

I’ve been seeing more and more people using splatting recently. I think I’m going to start using it in my code to clean things up and make it easier for people to add parameters to a command.

2

u/[deleted] Apr 06 '19

Thanks for this! I already have some scripts I want to go apply this to!

4

u/[deleted] Apr 05 '19

wow, that's interesting. so the takeaway is that you can pass an array to a cmdlet with the parameters. TIL. thnx

7

u/DrSinistar Apr 05 '19

pass a hashtable to a cmdlet

FTFY. They're different types. It's best not to confuse them.

5

u/TheIncorrigible1 Apr 05 '19

The article does a terrible job of explaining the feature; even the documentation is a better read.

You can pass arrays to splat a string array to external utilities (such as batch scripts, executables, etc.)

2

u/[deleted] Apr 05 '19

[removed] β€” view removed comment

3

u/TheIncorrigible1 Apr 05 '19

Yes, actual splatting. It's a neater way than writing out a long list of arguments; just like hashtable splatting for cmdlets.

2

u/[deleted] Apr 05 '19

[removed] β€” view removed comment

3

u/Lee_Dailey [grin] Apr 05 '19

howdy Szeraax,

for me, it is building an array of options for robocopy & then using that as the argument list for the util. it apparently works very much like that for other arguments. something like this ...

$RC_Params = @(
    $Source
    $Destination
    $FileSpec 
    # put your current options below
    "/Log:$FullLogFileName"
    '/E'
    '/TEE'
    )

robocopy $RC_Params

it aint what i consider splatting, but it fits well enuf & is documented as such ... but i can't find the silly docs for it right now. [blush]

take care,
lee

4

u/TheIncorrigible1 Apr 05 '19

That's not splatting. You're missing the syntax.

robocopy @RC_Params

4

u/ka-splam Apr 05 '19

What difference does it make?

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

4

u/TheIncorrigible1 Apr 05 '19

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

→ More replies (0)

2

u/Lee_Dailey [grin] Apr 05 '19

howdy TheIncorrigible1,

as i mentioned - it aint what i consider splatting. [grin] it's all positional or /ArgName:Value stuff. i had not tried it with an @ instead of a $ ... [blush]

take care,
lee

2

u/TheIncorrigible1 Apr 05 '19
$params = @( '/all' )
ipconfig @params

1

u/TheRealMisterd Apr 06 '19

What they don't tell you: splitting does not work with switches

6

u/halbaradkenafin Apr 06 '19

Yes it does, just pass it in as SwitchName = $true or $false and it'll pass in the switch correctly.

2

u/TheRealMisterd Apr 06 '19

This is new. Windows 7 with ps4 would give an error regardless of what you did.

1

u/PMental Apr 08 '19

Powershell 5+ works fine on Windows 7 though and was released 3 years ago so not exactly "new" :-)

0

u/[deleted] Apr 06 '19

[deleted]

5

u/sk82jack Apr 06 '19

Splatting is the action that you do to a hashtable. Build a hashtable where the keys are a function's parameters and then splat it to that particular function.

2

u/destruktive Apr 06 '19

Yup. This is why you refer to it with @ and not # so that PowerShell is aware that the objects in the hashtable is supposed to be used as parameters.

2

u/ColeMcDonald Apr 06 '19

I think it’s how you reference afterwards

3

u/[deleted] Apr 06 '19

[removed] β€” view removed comment

2

u/destruktive Apr 06 '19

Thank you, I really appreciate your feedback. I will certainly try to write more of these short tips as well as some more complicated stuff.