|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | + Dynamically Defines Aliases |
| 4 | +.DESCRIPTION |
| 5 | + Can Dynamically Define Aliases. |
| 6 | +
|
| 7 | + When uses in a parameter attribute, -Aliases will define a list of aliases. |
| 8 | +
|
| 9 | + When used with a variable, [Aliases] will Set-Alias on each value in the variable. |
| 10 | +.EXAMPLE |
| 11 | + { |
| 12 | + $aliases = "Foo", "Bar", "Baz" |
| 13 | + [Aliases(Command="Get-Process")]$aliases |
| 14 | + } | .>PipeScript |
| 15 | +.Example |
| 16 | + { |
| 17 | + param( |
| 18 | + [Aliases(Aliases={ |
| 19 | + ([char]'a'..[char]'z') |
| 20 | + })] |
| 21 | + [string] |
| 22 | + $Drive |
| 23 | + ) |
| 24 | + } | .>PipeScript |
| 25 | +#> |
| 26 | +[CmdletBinding(DefaultParameterSetName='AliasNames')] |
| 27 | +[Alias('SmartAlias','DynamicAlais')] |
| 28 | +param( |
| 29 | +# A list of aliases |
| 30 | +[Parameter(Mandatory,ParameterSetName='AliasNames')] |
| 31 | +[Alias('Alias')] |
| 32 | +[string[]] |
| 33 | +$Aliases, |
| 34 | + |
| 35 | +# If provided, will prefix each alias |
| 36 | +[string] |
| 37 | +$Prefix, |
| 38 | + |
| 39 | +# If provided, will add a suffix to each alias |
| 40 | +[string] |
| 41 | +$Suffix, |
| 42 | + |
| 43 | +# The command being aliased. This is only required when transpiling a variable. |
| 44 | +[Parameter(Mandatory,ParameterSetName='VariableExpressionAST')] |
| 45 | +[string] |
| 46 | +$Command, |
| 47 | + |
| 48 | +[Parameter(ParameterSetName='VariableExpressionAST')] |
| 49 | +[switch] |
| 50 | +$PassThru, |
| 51 | + |
| 52 | +# A VariableExpression. |
| 53 | +# If provided, this will be treated as the alias name or list of alias names. |
| 54 | +[Parameter(Mandatory,ValueFromPipeline,ParameterSetName='VariableExpressionAST')] |
| 55 | +[Management.Automation.Language.VariableExpressionAST] |
| 56 | +$VariableAST |
| 57 | +) |
| 58 | + |
| 59 | +process { |
| 60 | + if ($PSCmdlet.ParameterSetName -eq 'VariableExpressionAST') { |
| 61 | +[ScriptBlock]::Create($({ |
| 62 | +@(foreach ($alias in @($aliasNames)) { |
| 63 | + Set-Alias "${Prefix}$alias${Suffix}" "$Command" -PassThru:$PassThru |
| 64 | +}) |
| 65 | +} -replace '\${Prefix}', $Prefix -replace |
| 66 | + '\${Suffix}', $Suffix -replace |
| 67 | + '\$Command', $Command -replace |
| 68 | + '\$AliasNames', "$variableAst" -replace |
| 69 | + '\$PassThru', ('$' + ($PassThru -as [bool])) |
| 70 | +)) |
| 71 | + } else { |
| 72 | + $aliasValues = |
| 73 | + @(foreach ($alias in $aliasNames) { |
| 74 | + "$(if ($Prefix) { $Prefix })$alias$(if ($Suffix) { $Suffix })" |
| 75 | + }) |
| 76 | +[scriptblock]::Create("[Alias('$($Aliases -join "','")')]param()") |
| 77 | + } |
| 78 | +} |
| 79 | + |
0 commit comments