1

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.

Blaisem
  • 557
  • 8
  • 17
  • 1
    Just to highlight the root cause of your problem: Your alias definition is correct, (though can be simplified, as shown in Mathias' answer). Your only problem was the attempt to _directly_ execute a command whose name is stored in a _variable_ (`$textEditorAlias`), which in PowerShell requires `&`, the call operator, for _syntactic_ reasons - see [this answer](https://stackoverflow.com/a/57678081/45375) for why and when use of `&` is needed. – mklement0 Dec 30 '20 at 15:06

1 Answers1

4

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' }
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Yup. I was testing this to be sure it worked the way I thought, and arrived at the same answer - about a minute behind you. – Jeff Zeitlin Dec 30 '20 at 11:40
  • Awesome, thanks to both of you for your investigations :) – Blaisem Dec 30 '20 at 11:43
  • @JeffZeitlin I can assure you this was not the first time I've heard this specific point of confusion, I know too many bash-to-PowerShell converts ^_^ – Mathias R. Jessen Dec 30 '20 at 11:43
  • Helpful, but note that the problem was unrelated to the alias definition, which is correct (though it can be simplified, as you've shown). The sole problem was the attempt to invoke `$textEditorAlias` _without `&`_, and it is that which produced the error message. /cc @JeffZeitlin – mklement0 Dec 30 '20 at 15:11
  • 1
    @mklement0 Thanks, I just re-read the answer and even managed to confuse myself ^_^ Updated – Mathias R. Jessen Dec 30 '20 at 15:16