Discovering Dynamic Parameters

by Aug 4, 2015

In a previous tip we showed how you find cmdlets that expose dynamic parameters. Let's explore what the dynamic parameters are. The function Get-CmdletDynamicParameter returns a list of dynamic parameters and their default values:

#requires -Version 2
function Get-CmdletDynamicParameter
{
  param (
    [Parameter(ValueFromPipeline = $true,Mandatory = $true)]  
    [String] 
    $CmdletName
  )
 
  process
  {
    $command = Get-Command -Name $CmdletName -CommandType Cmdlet
    if ($command)
    {
      $cmdlet = New-Object -TypeName $command.ImplementingType.FullName
      if ($cmdlet -is [Management.Automation.IDynamicParameters])
      {
        $flags = [Reflection.BindingFlags]'Instance, Nonpublic'
        $field = $ExecutionContext.GetType().GetField('_context', $flags)
        $context = $field.GetValue($ExecutionContext)
        $property = [Management.Automation.Cmdlet].GetProperty('Context', $flags)
        $property.SetValue($cmdlet, $context, $null)
 
        $cmdlet.GetDynamicParameters()
      }
    }
  }
}

Get-CmdletDynamicParameter -CmdletName Get-ChildItem

The function uses some hacks to expose the dynamic parameters and was inspired by Dave Wyatt. See his full article at https://davewyatt.wordpress.com/2014/09/01/proxy-functions-for-cmdlets-with-dynamic-parameters/.

Twitter This Tip! ReTweet this Tip!