Created
July 20, 2023 04:22
-
-
Save quonic/540864c77a232802ff6dae2a94098f57 to your computer and use it in GitHub Desktop.
Get a PowerShell script's parameters and output certain aspects of each parameters. Utilizes the AST to get all its data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-Parameters { | |
param( | |
# Path to a .ps1 script | |
[string]$Path | |
) | |
begin {} | |
process { | |
$ScriptPath = Get-Item -Path $Path | |
$ScriptCommand = Get-Command $ScriptPath | |
$ScriptBlock = $ScriptCommand.ScriptBlock | |
$ScriptAst = $ScriptBlock.Ast | |
$ScriptParamBlock = $ScriptAst.ParamBlock | |
$ScriptParamBlock.Parameters | ForEach-Object { | |
$Parameter = $_ | |
$ParamMandatory = $false | |
$ParamSet = $null | |
$ParamType = $null | |
$ParamDefault = $Parameter.DefaultValue | |
$ParamName = $Parameter.Name | |
$Parameter.Attributes | ForEach-Object { | |
if ($_.TypeName -like "Parameter" -and $_.NamedArguments -and $_.NamedArguments.ArgumentName -like "Mandatory") { | |
$ParamMandatory = if ($Parameter.Attributes.NamedArguments.Argument -like '$true') { $true }else { $false } | |
} | |
elseif ($_.TypeName -like "ValidateSet" -and $_.PositionalArguments) { | |
$ParamSet = $_.PositionalArguments | |
} | |
else { | |
$ParamType = $_.TypeName | |
} | |
} | |
[PSCustomObject]@{ | |
ParamMandatory = $ParamMandatory | |
ParamSet = $ParamSet | |
ParamType = $ParamType | |
ParamDefault = $ParamDefault | |
ParamName = $ParamName | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param ( | |
# MyInt is a number | |
[Parameter(Mandatory = $true)] | |
[int]$MyInt = 10, | |
# MyBigInt is a big number | |
[Parameter(Mandatory = $false)] | |
[int64]$MyBigInt = 1GB, | |
# MyString is a string | |
[String]$MyString, | |
# MySet is a set string | |
[ValidateSet("A", "b")] | |
[String]$MySet, | |
# MySet is a switch | |
[switch]$MySwitch | |
) | |
begin { | |
Write-Host "Begin" | |
} | |
process { | |
Write-Host "Process" | |
} | |
end { | |
Write-Host "End" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment