tags:

views:

49

answers:

2

Is it possible to make Get-Variable always return variables in the order they've been declared?

 & {
     $c = 2
     $b = 1
     $a = 0

     get-variable -scope local
   }
A: 

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.)

Richard
I'm defining tests in scriptblocks and I'd like to run them in order.
guillermooo
You could put the tests in an array. Then the order would be guaranteed.
Keith Hill
Hm... Yeah, seems to be the obvious thing to do.
guillermooo
A: 

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.

guillermooo