IttayD
IttayD

Reputation: 29123

How can I set a shorthand alias for a variable?

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

Upvotes: 2

Views: 3624

Answers (3)

Jeter-work
Jeter-work

Reputation: 801

In order to access the value of a global variable, you merely have to call the variable.

    PS c:> $Global:LastResult = 'foo'
    PS c:> $LastResult
    foo

If you want to return an array or multiple answers, build a custom object and return it as the result of your function/cmdlet.

$LastResult = MyCustomCmdlet($Input)

$LastResult

<whatever custom object>

In Powershell, aliases are short names for cmdlets or functions. For a large number of examples, try:

Get-Alias

Or for just one, try:

Get-Alias gci

Upvotes: 0

Edo Duda
Edo Duda

Reputation: 7

You can:

Function CD32 {Set-Location -Path C:\Windows\System32}
Set-Alias -Name Go -Value CD32

Create an alias for a command with parameters

Upvotes: -1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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.

Upvotes: 3

Related Questions