Foreach Loop in PowerShell Not in Order -
i working config file powershell , every time call foreach loop grab data grabs in wrong order. see below:
config.ini
[queries] query01=stuff1 query02=stuff2 query03=stuff3 query04=stuff4
the foreach
loop:
#loads ini file data variable $inicontent = get-inicontent 'config.ini' #grabs hashtable data under [queries] section $queries = $inicontent['queries'] foreach($query in $queries.getenumerator()) { write-host $query.name }
i following output:
stuff1 stuff4 stuff2 stuff3
i assuming has asynchronous processing powershell, best way handle queries config.ini
file in order store them in there?
note: added number end of query (query01
) testing purposes. queries not have them in final config.ini
.
edit:
get-inicontent
function:
function get-inicontent ($filepath) { $ini = @{} switch -regex -file $filepath { “^\[(.+)\]” # section { $section = $matches[1] $ini[$section] = @{} $commentcount = 0 } “(.+?)\s*=(.*)” # key { $name,$value = $matches[1..2] $ini[$section][$name] = $value } } return $ini }
you need change both hashtable declarations ordered dictionaries. if change
$ini = @{}
to
$ini = [ordered]@{}
your $ini ordered dictionay nested hashtable created at
$ini[$section] = @{}
is still unordered hashtable. need change both of them ordered dictionaries.
function get-inicontent ($filepath) { $ini = [ordered]@{} switch -regex -file $filepath { “^\[(.+)\]” # section { $section = $matches[1] $ini[$section] = [ordered]@{} $commentcount = 0 } “(.+?)\s*=(.*)” # key { $name,$value = $matches[1..2] $ini[$section][$name] = $value } } return $ini }
edit
there convertto-ordereddictionary script on script center allows convert hashtables , arrays ordered dictionaries if don't want rewrite function.
Comments
Post a Comment