How to get variables in the order they are declared
Is it possible to make Get-Variable
always return variab开发者_运维百科les in the order they've been declared?
& {
$c = 2
$b = 1
$a = 0
get-variable -scope local
}
Turns out there is a way to achieve this if the variables are assigned scriptblocks (my case):
&{
$h_one = { "one" }
$h_two = { "two" }
$h_three = { "three" }
$h_four = { "four" }
$byStartLines= @{}
get-variable -name "h_*" -scope local | % { $byStartlines[($_.value.startposition.startline)] = $_ }
$order = ([int[]] $byStartLines.keys) | sort
$order | %{ $byStartLines[$_].name }
}
Things get more complicated if you declare several scripblocks in one line, but this is the gist of it.
I think the answer will be no, with a caveat.
Because there is nothing in the variable:name
entry (get this with dir variable:name
) that indicates when $name
was created.
The caveat would be a custom PSH host might be able to do something, by examining the pipelines in the runspace before execution (but this would likely require writing your own parser, and probably still wouldn't handle invoke-expression
).
(A better answer might be possible, if you explain why you want this.)
精彩评论