How can I set a shorthand alias for a variable?

后端 未结 2 1445
谎友^
谎友^ 2020-12-07 06:28

I am using a script that sets $Global:LastResult, how can I set an alias, say, last to access this variable

相关标签:
2条回答
  • 2020-12-07 06:37

    As TechNet description of Set-Alias goes:

    You can create an alias for a cmdlet, but you cannot create an alias for a command with parameters and values. For example, you can create an alias for Set-Location, but you cannot create an alias for Set-Location C:\Windows\System32. To create an alias for a command, create a function that includes the command, and then create an alias to the function.

    So you will need an alias to a function that simply returns your variable.

    0 讨论(0)
  • 2020-12-07 06:56

    You can't define an alias for a variable (well, technically you can, as long as the variable isn't $null, but then your alias would have the value of the variable at the time of the assignment).

    What you can do is define a function that returns the value of $global:LastResult and then an alias for that function:

    function Get-LastResult { $global:LastResult }
    New-Alias -Name last -Value Get-LastResult
    

    However, I fail to see the advantage of an approach like this over directly using the variable $global:LastResult.

    0 讨论(0)
提交回复
热议问题