Skip to content

Instantly share code, notes, and snippets.

@Geogboe
Last active July 30, 2018 20:30
Show Gist options
  • Save Geogboe/d00b1b36920eedee251b6a61d7e4b3d7 to your computer and use it in GitHub Desktop.
Save Geogboe/d00b1b36920eedee251b6a61d7e4b3d7 to your computer and use it in GitHub Desktop.
function New-ReusableCommandArgs {
<#
.SYNOPSIS
Creates a hashtable from the pararmters supplied to the function that has called this function
.DESCRIPTION
Determines which values are actually being used and returns them as a hash table
which can be easily platted to other commands
https://www.briantist.com/how-to/splatting-psboundparameters-default-values-optional-parameters/
#>
[cmdletbinding()]
param (
# List of string corresponding to paramters that should be included
# in the returned hashtable
[string[]]
$Only
# A paramter which, if found, will return INSTEAD of the params
# specified in "only"
# This allows for variable logic when calling this in a variety of functions
#[string]
#$Or
)
$FunctionThatCalledThisOne = ( Get-PSCallStack )[1]
$BoundParamsFromCallingFunction = $FunctionThatCalledThisOne.InvocationInfo.MyCommand.Parameters.GetEnumerator()
# Get all user supplied params and the data
$AllParams = @{}
foreach ( $Param in $BoundParamsFromCallingFunction ) {
$Key = $Param.Key
try {
$Variable = Get-Variable -Name $Key -ErrorAction Stop
$Val = $Variable | Select-Object -ExpandProperty Value -ErrorAction Stop
if ( ([String]::IsNullOrEmpty( $Val ) -and ( -not $PSBoundParameters.ContainsKey($key))) ) {
throw "A blank value that wasn't supplied by the caller."
}
Write-LogMessage "Key: {0}. Val: {1}" $Key, $Val -Type Debug
$AllParams[$Key] = $Val
}
catch {}
}
# return only the keys matching the string
if ( $Only ) {
$ReturnHashtable = @{}
foreach ( $Key in $Only ) {
if ( $AllParams.ContainsKey( $Key )) {
$ReturnHashtable.$Key = $AllParams.$Key
}
}
return $ReturnHashtable
}
else {
return $AllParams
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment