Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active May 13, 2024 02:21
Show Gist options
  • Save santisq/2b319c0e0776243fba7ddf6f3c5db5a5 to your computer and use it in GitHub Desktop.
Save santisq/2b319c0e0776243fba7ddf6f3c5db5a5 to your computer and use it in GitHub Desktop.
bind default values to `$PSBoundParameters`
& {
[CmdletBinding(DefaultParameterSetName = 'A')]
param(
[Parameter(ParameterSetName = 'A')]
$ParamA = 'A',
[Parameter(ParameterSetName = 'B')]
$ParamB = 'B',
[Parameter(Mandatory)]
$ParamBoth
)
foreach ($set in $MyInvocation.MyCommand.ParameterSets) {
if ($set.Name -ne $PSCmdlet.ParameterSetName) {
continue
}
foreach ($param in $set.Parameters) {
if ($PSBoundParameters.ContainsKey($param.Name)) {
continue
}
if ([System.Management.Automation.PSCmdlet]::CommonParameters.Contains($param.Name)) {
continue
}
if ([System.Management.Automation.PSCmdlet]::OptionalCommonParameters.Contains($param.Name)) {
continue
}
$PSBoundParameters[$param.Name] = $ExecutionContext.SessionState.PSVariable.GetValue($param.Key)
}
}
$PSBoundParameters
} -ParamBoth foo
& {
[CmdletBinding(DefaultParameterSetName = 'A')]
param(
[Parameter(ParameterSetName = 'A')]
$ParamA = 'A',
[Parameter(ParameterSetName = 'B')]
$ParamB = 'B',
[Parameter(Mandatory)]
$ParamBoth
)
$enum = [System.Management.Automation.CommandMetadata]::new($MyInvocation.MyCommand).
Parameters.GetEnumerator()
foreach ($param in $enum) {
if ($PSBoundParameters.ContainsKey($param.Key)) {
continue
}
if (-not $param.Value.ParameterSets.ContainsKey($PSCmdlet.ParameterSetName)) {
continue
}
$PSBoundParameters[$param.Key] = $ExecutionContext.SessionState.PSVariable.GetValue($param.Key)
}
$PSBoundParameters
} -ParamBoth foo
$null = [psmoduleinfo]::new{
Update-TypeData -MemberType ScriptMethod -MemberName SetParameterDefaultValues -Value {
$boundParams = $this.MyInvocation.BoundParameters
$enum = [System.Management.Automation.CommandMetadata]::new($this.MyInvocation.MyCommand).
Parameters.GetEnumerator()
foreach ($param in $enum) {
if ($boundParams.ContainsKey($param.Key)) {
continue
}
if (-not $param.Value.ParameterSets.ContainsKey($this.ParameterSetName)) {
continue
}
$boundParams[$param.Key] = $this.GetVariableValue($param.Key)
}
} -Force -TypeName ([System.Management.Automation.PSCmdlet])
}
& {
[CmdletBinding(DefaultParameterSetName = 'A')]
param(
[Parameter(ParameterSetName = 'A')]
$ParamA = 'A',
[Parameter(ParameterSetName = 'B')]
$ParamB = 'B',
[Parameter(Mandatory)]
$ParamBoth
)
$PSCmdlet.SetParameterDefaultValues()
$PSBoundParameters
} -ParamBoth foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment