开发者

Is there a shorthand form to get variables' values with numbered scopes?

开发者 https://www.devze.com 2022-12-25 01:36 出处:网络
Is there any shorter way of doing this in Powershell v2.0? & { $a = 1 ; & { $a = 2 ; & { get-variab开发者_运维百科le -name a -scope 2 } } }

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

& { $a = 1 ; & { $a = 2 ; & { get-variab开发者_运维百科le -name a -scope 2 } } }

... like, for instance, this?:

& { $a = 1 ; & { $a = 2 ; & { $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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消