Home > database >  How can I use an Alias as function parameter, In PowerShell?
How can I use an Alias as function parameter, In PowerShell?

Time:07-09

I have an Alias named "github", for example.

Set-Alias -Name github -Value "C:\UserName\Folder\github"

Also I have a function named "goto", for example:

Function goto ( [string] alias ) { Set-Location -Path $alias }

How can I use this function on my terminal passing as parameter an alias.

> goto github

Output: `cannnot find "CurrentLocation\github" folder, cause the function not resolve the alias as parameter

CodePudding user response:

An Alias, in simple terms, is just an association to a cmdlet, function, script file, or executable program. When we Set-Alias, what's happening is that a new AliasInfo instance is added to the Alias: PSDrive - See about Alias Provider for details.

So, to recap, when we do:

Set-Alias -Name github -Value "C:\UserName\Folder\github"

What's actually happening is that the the alias with name github is being associated with the function with name C:\UserName\Folder\github, a fun but useless demonstration:

PS /> Get-Alias github

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           github -> C:\UserName\Folder\github

PS /> ${function:C:\UserName\Folder\github} = { 'hello' }
PS /> C:\UserName\Folder\github
hello

PS /> github
hello

In my opinion, an easy workaround for what you're looking for would be to have one function (github) that outputs a string containing the path you want to access and a second function (goto) that receives the pipeline input, for this we use a non-advanced function that leverages the automatic variable $input:

function goto { Set-Location -Path $input }
function github { 'path\to\something' }

github | goto

Set-Alias would also be a valid use case for Set-Location since this cmdlet already accepts values from pipeline:

Set-Alias -Name goto -Value Set-Location
function github { 'path\to\something' }

github | goto

Alternatively, JPBlanc suggested, in a now deleted answer:

function goto ([string] $alias) { Set-Location -Path $alias }   
function githubpath { "C:\UserName\Folder\github" }

Which would also work for a positional argument but mandates the use of the grouping operator (..):

goto (github)

Why ?

Without the grouping operator, the function goto would see github as an argument and NOT as a separated function which we want to invoke.

The operator forces the github function to be invoked first or, in other words, to take precedence and to produce it's output before the invocation of the goto function.

  • Related