CodingAidsBD09.psm1

function New-SplattingTable {
  <#
  .SYNOPSIS
    This command builds a hashtable for PowerShell splatting
  .DESCRIPTION
    When using PowerShell commands on the commandline tab completion and Intellisense
    make it easy to discover the parameters for any given command. However when using
    PowerShell Splatting you need to be aware of all the possible parameters as these
    are typed into the hash table manually. This command can assist with automating
    the splatting table.
    This command takes a PowerShell Command Name as input and discovers the parameters
    that are available, it then creates a Splatting hashtable automatically and saves
    the code to the clipboard so that it can be easily added to a script. There is
    also an option to return the Splatting code as output and not have it saved in the
    clipboard.
  .PARAMETER CommandName
    This parameter accepts a PowerShell command name, it will also check to see if it
    recognises that command before proceeding
  .PARAMETER ShowSplat
    Instead of copying the splatting table to the clipboard this will display the
    hash table as output
  .NOTES
    Created By: Brent Denny
 
    Change Log
    ----------
    Who When Ver What
    ------------------- ----------- --- ------------------------------------------
    Brent Denny 05-Jun-2024 1.0 Just completed the module
    Brent Denny 05-Jun-2024 1.5 Made some minor adjustments to code and to the help
 
  .EXAMPLE
    New-SplattingTable -CommandName 'Get-Service'
    This example will find the non common parameters for the command Get-Service and
    arrange them in a hash table that will be then copied into the ClipBoard ready
    for pasting into your PowerShell script
  .EXAMPLE
    New-SplattingTable -CommandName 'Get-Service' -ShowSplat
    This example will find the non common parameters for the command Get-Service and
    arrange them in a hash table that will be displayed as output from this command
  #>

  [cmdletbinding()]
  Param (
    [Parameter(Mandatory=$true)]
    [string]$CommandName,
    [switch]$ShowSplat
  )
  # Get the command
  $CommandName = $CommandName.Trim()
  try {$CommandInfo = Get-Command -Name $CommandName -ErrorAction stop}
  catch {Write-Warning "$CommandName is not a valid command";break}
  
  # Create the start of the hash table
  $SplattingTable = "`$SplatTable = @{`n"
  
  # Populate the hash table with parameters
  $CommandInfo.Parameters.Keys | ForEach-Object {
    # Exclude common parameters
    if ($CommandInfo.Parameters[$_].ParameterType.Name -ne "SwitchParameter" -and 
        $_ -notin [System.Management.Automation.Cmdlet]::CommonParameters) {
      $SplattingTable = $SplattingTable + " $_" + " = ''`n"
    }
  }
  # Finish the hash table
  $SplattingTable = $SplattingTable + "}`n`n$CommandName `@SplatTable"
  # Decide to show or clipboard the splatting result
  if ($ShowSplat -eq $true) {return $SplattingTable}
  else {$SplattingTable | Set-Clipboard}
}