Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active October 26, 2022 21:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save indented-automation/56405ea6940f747c7b309e8b522bdeb4 to your computer and use it in GitHub Desktop.
Save indented-automation/56405ea6940f747c7b309e8b522bdeb4 to your computer and use it in GitHub Desktop.
PowerShell version 2 param block parser
function Get-CommandParameter {
# .SYNOPSIS
# A PowerShell version 2 compatible parameter block parser.
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)]
[String]$Definition
)
begin {
function Get-TokenGroup {
param (
[System.Management.Automation.PSToken[]]$tokens
)
$i = $j = 0
do {
$token = $tokens[$i]
if ($token.Type -eq 'GroupStart') {
$j++
}
if ($token.Type -eq 'GroupEnd') {
$j--
}
if (-not $token.PSObject.Properties.Item('Depth')) {
$token | Add-Member Depth -MemberType NoteProperty -Value $j
}
$token
$i++
} until ($j -eq 0 -or $i -ge $tokens.Count)
}
}
process {
$errors = $null
$tokens = [System.Management.Automation.PSParser]::Tokenize($Definition, [Ref]$errors)
# Find param
$start = $tokens.IndexOf(($tokens | Where-Object { $_.Content -eq 'param' })[0]) + 1
$paramBlock = Get-TokenGroup $tokens[$start..($tokens.Count - 1)]
for ($i = 0; $i -lt $paramBlock.Count; $i++) {
$token = $paramBlock[$i]
if ($token.Depth -eq 1 -and $token.Type -eq 'Variable') {
$paramInfo = New-Object PSObject -Property @{
Name = $token.Content
} | Select-Object Name, Type, DefaultValue, DefaultValueType
if ($paramBlock[$i + 1].Content -ne ',') {
$value = $paramBlock[$i + 2]
if ($value.Type -eq 'GroupStart') {
$tokenGroup = Get-TokenGroup $paramBlock[($i + 2)..($paramBlock.Count - 1)]
$paramInfo.DefaultValue = [String]::Join('', ($tokenGroup | ForEach-Object { $_.Content }))
$paramInfo.DefaultValueType = 'Expression'
} else {
$paramInfo.DefaultValue = $value.Content
$paramInfo.DefaultValueType = $value.Type
}
}
if ($paramBlock[$i - 1].Type -eq 'Type') {
$paramInfo.Type = $paramBlock[$i - 1].Content
}
$paramInfo
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment