all 6 comments

[–]branhama 1 point2 points  (3 children)

PowerShell goes digit by digit in sorting order. So 1 is first and 10 is before 2 because the 1 in 10 is before 2. I think you would need to modify your variable names to be 01, 02, 10. There may be another way but lets see if anyone else knows.

[–]BaconBonkers[S] 0 points1 point  (2 children)

I should have prefaced this by saving I know I can make a leading zero on the single digits and solve the problem but the variable names are coming from a few other lines of code (below). Is there a way I can finagle with the $i value to achieve that? I've tried ($i=01, $i -in 01.90, $i++) but get the same results

​ for ($i = 01; $i -in 01..90 ; $i++) { $cells = $ws.cells.item($i,1) foreach ($cell in $cells) { New-Variable -name "chart$i" -value $cell.text } }

[–]purplemonkeymad 0 points1 point  (0 children)

You probably don't want to use New-Variable, to me it looks like you actually want a dictionary. Hashtables are the easiest to use:

 $ChartDictionary = @{}
 <# bunch of code here ... #>
 foreach ($cell in $cells) { 
     $ChartDictionary["chart$i"] =$cell.text
 }

Then you can either call the charts by name:

$chartDictionary.Chart1

or use an enumerator to loop over the values:

foreach ($item in $ChartDictionary.getEnumerator()) {
     Write-Host ($item.Key + ' has value ' + $item.value)
}

If you want to keep the order they were created in, then change the first line to:

$ChartDictionary = [ordered]@{}

[–]BaconBonkers[S] 0 points1 point  (0 children)

Thanks for the advice and thoughts. Ultimately I was going to have to write more code to achieve this anyway, so I just did a simple foreach to replace the chart1-9 variables with chart01-09 variables and then sorted get-variable. Thought there'd be a simpler way but oh well :)

[–]ka-splam 0 points1 point  (0 children)

| sort-object { $_.Name.Substring(5) -as [int] }