Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Why can't I add aliases in functions?

I tried adding several aliases in my powershell profile script. For organization reasons I wanted to keep those in a function which I would call at the end of said profile. I discovered that, while the function can be called from inside or outside the script without any problems, the aliases don't apply to my current powershell session. Only when I add them one at a time in the profile script, they would be usable.

This is my script as it is right now

function Populate-Aliases() {
  New-Alias grep Select-String
  New-Alias touch New-Item
  New-Alias lsa dir -Force
}

Populate-Aliases

I'm also certain the script is executed when I create a new ps session, as is proven by inserting any output in the function. It's just the aliases that don't apply to my session.

I tried creating the aliases via function in the profile script, which didn't work. I also tried declaring a function from within the terminal as such:

function al(){New-Alias lsa dir -Force}
al
lsa

This did also not work which leads me to believe that I'm making some kind of mistake or creating aliases in functions is not supported (which I could not quite understand why that would be the case).

Creating an alias via New-Alias in the cli works without any problem. Also just adding the New-Alias statement to the profile script works, when it is not enclosed in a function.

like image 763
Laszlo Stark Avatar asked Sep 07 '25 18:09

Laszlo Stark


1 Answers

-Scope
Specifies the scope in which this alias is valid. The default value is Local. For more information, see about_Scopes.

This means that, by default, the concerned alias is only available in the scope of the function:

function Test {
    New-Alias Show Write-Host
    Show 'This works'
}
Test
Show 'but this does not work'

Unless you will set the -scope to global:

function Test {
    New-Alias -Scope Global Show Write-Host
    Show 'This works'
}
Test
Show 'And this works too'
like image 167
iRon Avatar answered Sep 09 '25 23:09

iRon