
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:
Get-ChildItem -Path 'C:\' -Depth 2With splatting, you can create an object containing each parameter and its respective value, like this:
$GetChildItemSplat = @{
Path = 'C:\\'
Depth = 2
}
Get-ChildItem @GetChildItemSplatAdditionally, you can splat using an array, as demonstrated in Microsoft’s documentation:
$ArrayArguments = "test.txt", "test2.txt"
Copy-Item @ArrayArgumentsThe 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:
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:
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:
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:
Invoke-MyGetChildItem -Path 'c:\' -Depth 2Lastly, consider splatting with script blocks:
$StartJobSplat = @{
Name = 'Test Job'
ScriptBlock = {
Get-ChildItem -Path 'C:\'
}
}
Start-Job @StartJobSplatIncorporating splatting into your PowerShell scripts can greatly enhance their readability and maintainability.
