PoshCode Archive  Artifact [f5d2aea8a2]

Artifact f5d2aea8a2f0fa18fd3aac7beded9fd223c1826a4424e75183b04c1512f13a30:

  • File Get-Constructor.ps1 — part of check-in [9493565b94] at 2018-06-10 13:02:08 on branch trunk — Enumerates the constructors of a type with the parameters that they take, so you can figure out what your options are when calling New-Object. Now outputs fully paste-able syntax ;) (user: Joel Bennett size: 1575)

# encoding: ascii
# api: powershell
# title: Get-Constructor
# description: Enumerates the constructors of a type with the parameters that they take, so you can figure out what your options are when calling New-Object. Now outputs fully paste-able syntax ;)
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Get-Constructor
# x-poshcode-id: 1862
# x-archived: 2010-05-24T16:40:42
#
#
function Get-Constructor {
PARAM( [Type]$type, [Switch]$Simple)
   if($Simple) {
   $type.GetConstructors() | 
      Select @{
         l="$($type.Name) Constructor"
         e={ "New-Object $($type.FullName) $(($_.GetParameters() | ForEach { "[{0}]`${1}" -f $_.ParameterType.FullName, $_.Name }) -Join ", ")" }
      }
   } else {
   $type.GetConstructors() | 
      Select @{
         name = "$($type.Name) Constructors"
         expression = { 
            $parameters = $(
               foreach($param in $_.GetParameters()) {
                  Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan
                  
                  if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' }
                  if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' }
                  '{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.FullName.TrimEnd('&'), $param.Name
               }
            )
         
            "New-Object $($type.FullName) $($parameters -join ', ')"
         }
      }
   }
}

Set-Alias gctor Get-Constructor