I can’t get PowerShell aliases to work. My code (called at the beginning of my script):
function Set-Aliases {
Set-Alias -name csttc -value Convert-ServerTypeToTitleCase
}
Later, I call it like this:
Confirm-ChangeSuccess -item "$(csttc -server $server) user" -newValue $newValue
It returns this error message:
The term 'csttc' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
What am I doing wrong? I'm running Visual Studio Code 1.81.0. My $PSVersionTable
PSVersion 7.3.6
PSEdition Core
GitCommitId 7.3.6
OS Microsoft Windows 10.0.19045
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
In PowerShell, aliases, like functions and variables, are scoped, and by default they are created in the current scope, which means that only that scope and its descendants see it.
Since functions execute in a child scope when invoked directly (or via &
), your alias definition was only visible inside your Set-Aliases
definition and went out of scope when the function returned.
Therefore:
To define your aliases in the caller's scope (whatever it may be), dot-source your function:
# Dot-sourcing (`. `) runs the function directly in the caller's scope.
. Set-Aliases
$PROFILE
files are implicitly dot-sourced, so if you place Set-Alias
calls directly in such a file, they will become globally available in the session.To define your aliases globally (whatever scope you're calling from), define your function as follows - regular invocation will then do:
# Note the use of `-Scope Global`
function Set-Aliases {
Set-Alias -Scope Global -Name csttc -Value Convert-ServerTypeToTitleCase
}
# Normal invocation now defines the alias *globally*
Set-Aliases