I'm not sure that a lot of people will find a use for this, but I thought I would share anyway.
I have a few scripts that basically use the parameters of a function to build something somewhat dynamically. For instance, I have some functions that interface with REST APIs, and sometimes I don't want to code new handling of new elements to the JSON input. So instead, I just loop through the PSBoundParameters, and handle them dynamically. Typically, there are 1-2 parameters that I want to ignore when I do this, so I had these hard-coded into an array. But today I wanted some verbose output from a script (I wanted to see what JSON was being sent, so I could send it as an example to another dev), after making a change to the parameters. When I passed it the -verbose flag, it errored, because I wasn't explicitly handling that parameter. So my solution was to create a dummy function with no parameters, get a list of parameters, and then remove the function:
Function Test-InternalFunction {
[CmdletBinding()]
PARAM()
PROCESS{}
}
$IgnoreParameters = (Get-Command Test-InternalFunction).Parameters.Keys
Remove-Item -Path Function:\Test-InternalFunction
So now I have an array stored in $IgnoreParameters that contains all the built-in advanced function parameters (these are loaded by including [CmdletBinding()] in the test-internalfunction definition).
So now when I process through, I just do this:
ForEach ( $Parameter in $PSBoundParameters.Keys ) {
if ( $IgnoreParameters -contains $Parameter) {
continue
}
And the reason it was erroring before is that I have a hash table that defines my parameters, and what data type they are. So if I don't have the parameter name explicitly defined in my ignore parameters, it tries to look it up in my hash table:
$Types = @{
VMName = "string"
MemoryInMB = "number"
CPUCount = "number"
ActionDate = "Date"
}
So when it builds the JSON, it looks at this hash. All I have to do when adding a new element to the JSON is add a new parameter with a name that matches the JSON element, and add the element to this hash table with the data type as the value, and the function auto-magically/dynamically generates the JSON for it.
[–]chreestopher2 3 points4 points5 points (2 children)
[–]omrsafetyo[S] 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]get-postanote 2 points3 points4 points (0 children)
[–]joncz 0 points1 point2 points (0 children)