PoshCode Logo PowerShell Code Repository

Get-Parameter 2.3 by Joel Bennett 18 months ago (modification of post by Joel Bennett view diff)
View followups from Joel Bennett | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2031"></script>download | new post

  1. #Requires -version 2.0
  2.  
  3. #.Synopsis
  4. #  Enumerates the parameters of one or more commands
  5. #.Notes
  6. #  With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy
  7. #  Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186
  8. #  Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255
  9. #  Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445
  10. #  Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446
  11. #  Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549
  12. #               - Added resolving aliases and avoided empty output
  13. #  Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344
  14. #  Version 1.0  - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592
  15. #               - Merged Oisin and Hal's code with my own implementation
  16. #               - Added calculation of dynamic paramters
  17. #  Version 2.0  - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005
  18. #               - Now uses FormatData so the output is objects
  19. #               - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation)
  20. #  Version 2.1  - July 22, 2010 - By Joel Bennett http://poshcode.org/2007
  21. #               - Fixed Help for SCRIPT file (script help must be separated from #Requires by an emtpy line)
  22. #               - Fleshed out and added dates to this version history after Bergle's criticism ;)
  23. #  Version 2.2  - July 29, 2010 - By Joel Bennett (This Version)
  24. #               - Fixed a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo
  25. #  Version 2.3  - July 29, 2010 - By Joel Bennett (This Version)
  26. #               - Added a ToString ScriptMethod which allows queries like:
  27. #                 $parameters = Get-Parameter Get-Process; $parameters -match "Name"
  28. #
  29. #.Description
  30. #  Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
  31. #
  32. #  By default, formats the output to tables grouped by command and parameter set
  33. #.Example
  34. #  Get-Command Select-Xml | Get-Parameter
  35. #.Example
  36. #  Get-Parameter Select-Xml
  37. #.Parameter Name
  38. #  The name of the command to get parameters for
  39. #.Parameter ModuleName
  40. #  The name of the module which contains the command (this is for scoping)
  41. #.Parameter Force
  42. #  Forces including the CommonParameters in the output
  43. [CmdletBinding()]
  44. ##This is just script-file nesting stuff, so that you can call the SCRIPT, and after it defines the global function, it will call it.
  45. param (
  46.    [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
  47.    [string[]]$Name
  48. ,
  49.    [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
  50.    $ModuleName
  51. ,
  52.    [switch]$Force
  53. )
  54.  
  55. Function global:Get-Parameter {
  56. #.Synopsis
  57. #  Enumerates the parameters of one or more commands
  58. #.Description
  59. #  Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
  60. #
  61. #  By default, formats the output to tables grouped by command and parameter set
  62. #.Example
  63. #  Get-Command Select-Xml | Get-Parameter
  64. #.Example
  65. #  Get-Parameter Select-Xml
  66. #.Parameter Name
  67. #  The name of the command to get parameters for
  68. #.Parameter ModuleName
  69. #  The name of the module which contains the command (this is for scoping)
  70. #.Parameter Force
  71. #  Forces including the CommonParameters in the output
  72. [CmdletBinding()]
  73. param (
  74.    [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
  75.    [string[]]$Name
  76. ,
  77.    [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
  78.    $ModuleName
  79. ,
  80.    [switch]$Force
  81. )
  82. begin {
  83.    $PropertySet = @( "Name",
  84.                      @{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}},
  85.                      "Aliases",
  86.                      @{n="Short";e={$_.Name}},
  87.                      @{n="Type";e={$_.ParameterType.Name}},
  88.                      @{n="ParameterSet";e={$paramset}},
  89.                      @{n="Command";e={$command}},
  90.                      @{n="Mandatory";e={$_.IsMandatory}},
  91.                      @{n="Provider";e={$_.DynamicProvider}},
  92.                      @{n="ValueFromPipeline";e={$_.ValueFromPipeline}},
  93.                      @{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}}
  94.                   )
  95.    function Join-Object {
  96.    Param(
  97.       [Parameter(Position=0)]
  98.       $First
  99.    ,
  100.       [Parameter(ValueFromPipeline=$true,Position=1)]
  101.       $Second
  102.    )
  103.       begin {
  104.          [string[]] $p1 = $First | gm -type Properties | select -expand Name
  105.       }
  106.       process {
  107.          $Output = $First | Select $p1
  108.          foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
  109.             Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
  110.          }
  111.          $Output
  112.       }
  113.    }
  114. }
  115. process{
  116.    foreach($cmd in $Name) {
  117.       if($ModuleName)   { $cmd = "$ModuleName\$cmd" }
  118.       $commands = @(Get-Command $cmd)
  119.  
  120.       foreach($command in $commands) {
  121.          # resolve aliases (an alias can point to another alias)
  122.          while ($command.CommandType -eq "Alias") {
  123.             $command = @(Get-Command ($command.definition))[0]
  124.          }
  125.          if (-not $command) { continue }
  126.  
  127.          $Parameters = @{}
  128.  
  129.          foreach($provider in Get-PSProvider) {
  130.             $drive = "{0}\{1}::\" -f $provider.ModuleName, $provider.Name
  131.             Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters")
  132.            
  133.             [Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values
  134.             [Array]$Dynamic = $MoreParameters | Where { $_.IsDynamic }
  135.              
  136.             foreach($p in $MoreParameters | Where { $Dynamic -notcontains $_ } ){
  137.                $Parameters.($p.Name) = $p
  138.             }
  139.            
  140.             # Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)"
  141.             if($dynamic) {
  142.                foreach($d in $dynamic) {
  143.                   if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) {
  144.                      Write-Debug ("ADD:" + $d.Name + " " + $provider.Name)
  145.                      $Parameters.($d.Name).DynamicProvider += $provider.Name
  146.                   } else {
  147.                      Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name)
  148.                      $Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru
  149.                   }
  150.                }
  151.             }
  152.          }
  153.          
  154.          ## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else.
  155.          foreach($p in $($Parameters.Keys))
  156.          {
  157.             $shortest="^"
  158.             foreach($char in [char[]]$p)
  159.             {            
  160.                $shortest += $char
  161.                $Matches = ($Parameters.Keys -match $Shortest).Count
  162.                Write-Debug "$($shortest.SubString(1)) $Matches"
  163.                if($Matches -eq 1)
  164.                {
  165.                   $Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru
  166.                   break
  167.                }
  168.             }
  169.          }
  170.    
  171.          Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)"
  172.        
  173.          foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){
  174.             foreach($parameter in $Parameters.Keys | Sort) {
  175.                Write-Verbose "Parameter: $Parameter"
  176.                if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue }
  177.                if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) {                  
  178.                   if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) {
  179.                      $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet
  180.                   } else {
  181.                      $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets
  182.                   }
  183.                  
  184.                  
  185.                  
  186.                   Write-Output $Output | Select-Object $PropertySet | ForEach {
  187.                      $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata")
  188.                      $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx")
  189.                      Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")"
  190.                      $_
  191.                   } | Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru
  192.                }
  193.             }
  194.          }
  195.       }
  196.    }
  197. }
  198. }
  199.  
  200.  
  201. # Since you can't update format data without a file that has a ps1xml ending, let's make one up...
  202. $tempFile = "$([IO.Path]::GetTempFileName()).ps1xml"
  203. Set-Content $tempFile @'
  204. <?xml version="1.0" encoding="utf-8" ?>
  205. <Configuration>
  206.    <Controls>
  207.        <Control>
  208.            <Name>ParameterGroupingFormat</Name>
  209.              <CustomControl>
  210.                  <CustomEntries>
  211.                      <CustomEntry>
  212.                          <CustomItem>
  213.                              <Frame>
  214.                                  <LeftIndent>4</LeftIndent>
  215.                                  <CustomItem>
  216.                                      <Text>Command: </Text>
  217.                                      <ExpressionBinding>
  218.                                          <ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock>
  219.                                      </ExpressionBinding>
  220.                                      <NewLine/>
  221.                                      <Text>Set:     </Text>
  222.                                      <ExpressionBinding>
  223.                                          <ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock>
  224.                                      </ExpressionBinding>
  225.                                      <NewLine/>
  226.                                  </CustomItem>
  227.                              </Frame>
  228.                          </CustomItem>
  229.                      </CustomEntry>
  230.                  </CustomEntries>
  231.            </CustomControl>
  232.        </Control>
  233.    </Controls>
  234.    <ViewDefinitions>
  235.        <View>
  236.            <Name>ParameterMetadataEx</Name>
  237.            <ViewSelectedBy>
  238.                <TypeName>System.Management.Automation.ParameterMetadataEx</TypeName>
  239.            </ViewSelectedBy>
  240.            <GroupBy>
  241.                <PropertyName>ParameterSet</PropertyName>
  242.                <CustomControlName>ParameterGroupingFormat</CustomControlName>  
  243.            </GroupBy>
  244.            <TableControl>
  245.                <TableHeaders>
  246.                    <TableColumnHeader>
  247.                        <Label>Name</Label>
  248.                        <Width>22</Width>
  249.                    </TableColumnHeader>
  250.                    <TableColumnHeader>
  251.                        <Label>Aliases</Label>
  252.                        <Width>12</Width>
  253.                    </TableColumnHeader>
  254.                    <TableColumnHeader>
  255.                        <Label>Position</Label>
  256.                        <Width>8</Width>
  257.                    </TableColumnHeader>
  258.                    <TableColumnHeader>
  259.                        <Label>Mandatory</Label>
  260.                        <Width>9</Width>
  261.                    </TableColumnHeader>
  262.                    <TableColumnHeader>
  263.                        <Label>Pipeline</Label>
  264.                        <Width>8</Width>
  265.                    </TableColumnHeader>
  266.                    <TableColumnHeader>
  267.                        <Label>ByName</Label>
  268.                        <Width>6</Width>
  269.                    </TableColumnHeader>
  270.                    <TableColumnHeader>
  271.                        <Label>Provider</Label>
  272.                        <Width>15</Width>
  273.                    </TableColumnHeader>
  274.                    <TableColumnHeader>
  275.                        <Label>Type</Label>
  276.                    </TableColumnHeader>
  277.                </TableHeaders>
  278.                <TableRowEntries>
  279.                    <TableRowEntry>
  280.                        <TableColumnItems>
  281.                            <TableColumnItem>
  282.                                <PropertyName>Name</PropertyName>
  283.                            </TableColumnItem>
  284.                            <TableColumnItem>
  285.                                <PropertyName>Aliases</PropertyName>
  286.                            </TableColumnItem>
  287.                            <TableColumnItem>
  288.                                <!--PropertyName>Position</PropertyName-->
  289.                                <ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock>
  290.                            </TableColumnItem>
  291.                            <TableColumnItem>
  292.                                <PropertyName>Mandatory</PropertyName>
  293.                            </TableColumnItem>
  294.                            <TableColumnItem>
  295.                                <PropertyName>ValueFromPipeline</PropertyName>
  296.                            </TableColumnItem>
  297.                            <TableColumnItem>
  298.                                <PropertyName>ValueFromPipelineByPropertyName</PropertyName>
  299.                            </TableColumnItem>
  300.                            <TableColumnItem>
  301.                                <!--PropertyName>Provider</PropertyName-->
  302.                                <ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock>
  303.                            </TableColumnItem>
  304.                            <TableColumnItem>
  305.                                <PropertyName>Type</PropertyName>
  306.                            </TableColumnItem>
  307.                        </TableColumnItems>
  308.                    </TableRowEntry>
  309.                 </TableRowEntries>
  310.            </TableControl>
  311.        </View>
  312.    </ViewDefinitions>
  313. </Configuration>
  314. '@
  315.  
  316. Update-FormatData -Append $tempFile
  317.  
  318.  
  319. # This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that.
  320. Get-Parameter @PSBoundParameters

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me