views:

34

answers:

2

Is there any shorter way of doing this in Powershell v2.0?

& { $a = 1 ; & { $a = 2 ; & { get-variable -name a -scope 2 } } }

... like, for instance, this?:

& { $a = 1 ; & { $a = 2 ; & { $2:a } } }
+2  A: 

I do not believe there is a shortcut for scoping - it appears to be only accessible by using the -scope argument. However, a function could encapsulate the work:

function Get-ScopedVariable([string]$name, [int]$scope) {
    Get-Variable -name $name -scope ($scope + 1) # add one for the extra-scope of this function
}

Your example would then be shortened to:

& { $a = 1 ; & { $a = 2 ; & { Get-ScopedVariable a 2 } } }

The function could then be aliased to further shorten it.

James Kolpack
I neglected to mention that I was asking about built-in shortcuts besides aliases, but this answer is the most adequate to the actual question.
guillermooo
+2  A: 

There are a number of default aliases, one of which happens to be gv for Get-Variable:

gv -Name a -Scope 2

Furthermore you don't need to supply the -Name parameter explicitly as it's inferred to be the first argument:

gv a -Scope 2

And you don't need to write out the complete parameter name and can shorten it (as long as it remains unambiguous):

gv a -s 2

Mind you, you shouldn't do this in scripts you intend to distribute but for something quick on the command line this is certainly valid.

Joey