SplatHelper.psm1
function ConvertTo-Splatting { <# Converts a single statement, with named parameters #> [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true, Position = 0, Mandatory = $true)] [string] $Command ) $sb = [scriptblock]::Create($Command); $elements = $sb.Ast.EndBlock.Statements[0].PipelineElements[0].CommandElements; ### If there aren't any command elements, then skip ### This is just a safeguard if (!$elements) { Write-Warning -Message 'No command elements found'; return } $SplattingString = '$Params = @{{{0}' -f "`n"; foreach ($Element in $elements) { if ($Element -is [System.Management.Automation.Language.CommandParameterAst]) { $ParameterName = $Element.ParameterName; $Value = $elements[$elements.IndexOf($Element) + 1]; switch ($Value.GetType().Name) { { $PSItem -in @('StringConstantExpressionAst', 'ArrayLiteralAst') } { if ($Value.StringConstantType -eq 'SingleQuoted') { $SplattingString += ' {0} = {1};{2}' -f $ParameterName, $Value.Extent.Text, "`n"; } else { $SplattingString += ' {0} = ''{1}'';{2}' -f $ParameterName, $Value.Extent.Text, "`n"; } break; } { $PSItem -in @('VariableExpressionAst', 'ParenExpressionAst') } { $SplattingString += ' {0} = {1};{2}' -f $ParameterName, $Value.Extent.Text, "`n"; break; } { $PSItem -in @('HashTableAst') } { $SplattingString += ' {0} = @{{{1}' -f $ParameterName, "`n"; foreach ($Pair in $Value.KeyValuePairs) { $SplattingString += ' {0} = {1};{2}' -f $Pair.Item1, $Pair.Item2, "`n"; } $SplattingString += ' }}{0}' -f "`n"; } } } } $SplattingString += ' }}{0}' -f "`n"; $SplattingString += '{0} @Params' -f $elements[0].Extent.Text; Write-Output -InputObject $SplattingString; } function Convert-ISELineToSplatting { <# .Synopsis Converts the current line in PowerShell ISE to a Splatting call #> [CmdletBinding()] param () $File = $psISE.CurrentFile.Editor.Text.Split("`n"); $Result = ConvertTo-Splatting -Command $psISE.CurrentFile.Editor.CaretLineText; if (!$Result) { Write-Warning -Message 'No changes were made'; return; } $File[$psISE.CurrentFile.Editor.CaretLine-1] = $Result; $File = $File -join "`n"; $psISE.CurrentFile.Editor.Text = $File; } New-Alias -Name splat -Value ConvertTo-Splatting -Force; New-Alias -Name splatise -Value Convert-ISELineToSplatting -Force; |