Blaisem
Blaisem

Reputation: 637

Reference alias as variable in function

I am setting up my PowerShell profile and would like to define the alias I use for my text editor as a variable, so that if I port my profile to others, they would be free to define the alias as they wish.

Here are some of the first few lines of my profile:

$textEditorAlias = 'np'
$textEditorExecutable = 'notepad++.exe'

set-alias -name $textEditorAlias -value (get-command $textEditorExecutable).path -scope Global -Option AllScope

# Shortcuts to commonly used files.
function frequentFile { $textEditorAlias 'C:\<pathToFile>\fileName' }

My problem is the function above returns "unexpected token in expression or statement".

If I replace the function with

function frequentFile { np 'C:\<pathToFile>\fileName' }

then it works.

Is there a way to have the variable $textEditorAlias expand within the function's expression cleanly?

Thank you.

Upvotes: 1

Views: 259

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Aliases in PowerShell are dead simple - AliasName -> CommandName - no arguments, no customization, just plain name-to-name mappings.

This means you don't need to call Get-Command explicitly - PowerShell will do that for you automatically:

$textEditorAlias = 'np'
$textEditorExecutable = 'notepad++.exe'
Set-Alias -Name $textEditorAlias -Value $textEditorExecutable

My problem is the function above returns "unexpected token in expression or statement".

If you want to invoke a command based on a string variable, use the & invocation operator:

$textEditorAlias = 'np'
function frequentFile { & $textEditorAlias 'C:\<pathToFile>\fileName' }

Upvotes: 4

Related Questions