Skip to content

Instantly share code, notes, and snippets.

@quonic
Created July 20, 2023 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quonic/540864c77a232802ff6dae2a94098f57 to your computer and use it in GitHub Desktop.
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.
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
}
}
}
}
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