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
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 what is expected to be a command, cmdlet or function but in this case is just a string containing a path.
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
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)
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.
Another workaround would be to have just the goto function that has a definition with paths of interest in the form of a hash table:
function goto {
param([Parameter(Mandatory)] $Path)
$map = @{
github = "C:\UserName\Folder\github"
foo = "path\to\foo"
bar = "path\to\bar"
}
$map[$Path] | Set-Location
}
goto github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With