r/PowerShell • • Apr 05 '19

PowerShell tricks: Splatting

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

58 comments sorted by

View all comments

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 🙂