powershellaliasscoping

Can't Create a Powershell Alias


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

Solution

  • 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: