powershelluser-defined-functionsaliaswindows-11user-defined

powershell user defined function not working with an alias - odd error message


working in Windows 11 with PowerShell 7.5.1 (NOT Windows PowerShell)

i have some functions and aliases defined in

C:\Users\Jeff\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

here are the definitions

Function envvar { param ([string]$varname) gci env`:$varname }

new-alias -name envvar -value envvar

new-alias -name testvar -value envvar

in a new PS window i do command Get-Alias to see the list of defined aliases and mine is in the list

Alias           envvar -> envvar

but when i do command envvar PATH i get this:

PS C:\Users\Jeff> envvar PATH
envvar: The term 'envvar' 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.

[general]
  The most similar commands are:
    > envvar

so maybe the problem is that i used the same name for the alias and the function, but no:

PS C:\Users\Jeff> testvar PATH
testvar: The term 'testvar' 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.
PS C:\Users\Jeff>

i have not found a way to list user defined functions so i cant tell if the function is correctly defined .. but i suspect not

my goal is to have a PS command that can return a (formatted, or at least split) list of the elements in one of the paths PATH, LIB, or LIBPATH


Solution

  • Aliases always point to a command, you can see this by inspecting the .ResolvedCommand property on AliasInfo instances:

    function foo { 1 + 1 }
    New-Alias -Name bar -Value foo
    (Get-Command bar).ResolvedCommand
    
    # CommandType     Name                    Version    Source
    # -----------     ----                    -------    ------
    # Function        foo
    

    However, by naming an alias that points to a function with the same name you're effectively creating an alias that points to nowhere:

    New-Alias -Name foo -Value foo
    (Get-Command foo).ResolvedCommand # null, points to no command
    

    Though you can see the function still exists:

    Get-Command foo -CommandType Function
    
    # CommandType     Name         Version    Source
    # -----------     ----         -------    ------
    # Function        foo
    

    And said function can be invoked via CommandInfo object or Provider path:

    & (Get-Command foo -CommandType Function) # 2
    & $function:foo # 2
    

    Simple solution to the problem is to remove the New-Alias line from your $PROFILE:

    New-Alias -Name envvar -Value envvar