How to Master PowerShell Splatting: Unraveling the Mystery

PowerShell
PowerShell Splatting, not Nickelodeon splatting!

I said PowerShell splatting…

PowerShell splatting, although widely recognized among PowerShell users, is often overlooked within the community.

Splatting simplifies command parameter organization by allowing you to bundle them into an object, which can then be passed into a function. The function interprets the object members as individual parameters, enhancing code clarity and readability.

For example, when calling the Get-ChildItem function to set the path to C:\ with a recursion depth of 2, you can achieve it as follows:

PowerShell
Get-ChildItem -Path 'C:\' -Depth 2

With splatting, you can create an object containing each parameter and its respective value, like this:

PowerShell
$GetChildItemSplat = @{
    Path = 'C:\\'
    Depth = 2 
}

Get-ChildItem @GetChildItemSplat

Additionally, you can splat using an array, as demonstrated in Microsoft’s documentation:

PowerShell
$ArrayArguments = "test.txt", "test2.txt"
Copy-Item @ArrayArguments

The benefits of splatting include:

  • Enhanced code readability
  • Improved error detection
  • Facilitation of more complex parameter logic without sacrificing readability

Now, let’s explore a scenario where splatting can be particularly useful. Consider the following example involving the Get-ChildItem function:

PowerShell
Function Invoke-MyGetChildItem {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$Path,
        [Parameter(Mandatory)]
        [int]$Depth
    )
    Get-ChildItem @PSBoundParameters
}

Avoid repetitive coding practices like the one shown below:

PowerShell
Function Invoke-MyGetChildItem {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$Path,
        [Parameter(Mandatory)]
        [int]$Depth
    )
    $ChildItemSplat = @{
        Path = $Path
        Depth = $Depth
    }
    Get-ChildItem @ChildItemSplat
}

Utilizing $PSBoundParameters ensures only explicitly called parameters are passed. Now, let’s introduce an additional optional parameter, ItemType, to the function:

PowerShell
Function Invoke-MyGetChildItem {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$Path,
        [Parameter(Mandatory)]
        [int]$Depth,
        [string]$ItemType
    )
    Write-Output $PSBoundParameters
    #Get-ChildItem @PSBoundParameters
}

This function can be called without specifying the ItemType parameter:

PowerShell
Invoke-MyGetChildItem -Path 'c:\' -Depth 2

Lastly, consider splatting with script blocks:

PowerShell
$StartJobSplat = @{
    Name = 'Test Job'
    ScriptBlock = {
        Get-ChildItem -Path 'C:\'
    }
}

Start-Job @StartJobSplat

Incorporating splatting into your PowerShell scripts can greatly enhance their readability and maintainability.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights