PowerShell中的Foreach循环顺序不正确

4

我正在处理一个 PowerShell 的配置文件,每次调用 foreach 循环获取数据时,它都会以错误的顺序获取。如下所示:

config.ini

[queries]

query01=stuff1

query02=stuff2

query03=stuff3

query04=stuff4
<代码>foreach循环:
#Loads an INI file data into a variable
$iniContent = Get-IniContent 'config.ini'
#grabs the hashtable for the data under the [queries] section
$queries = $iniContent['queries']

foreach($query in $queries.GetEnumerator())
{
    write-host $query.name
}

我得到了以下输出:
stuff1
stuff4
stuff2
stuff3

我假设这与PowerShell的异步处理有关,但是如何以我在config.ini文件中存储的顺序处理查询最好呢?
注意:我为测试目的在查询结尾添加了编号(query01)。在我最终的config.ini中将不包含它们。
编辑: Get-IniContent函数:
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
}
2个回答

8

您需要将两个哈希表声明更改为有序字典。如果只更改一个,程序可能会出现错误。

$ini = @{}

to

$ini = [ordered]@{}

你的$ini现在是一个有序字典,但在创建的嵌套哈希表中

$ini[$section] = @{}

仍然是无序哈希表。你需要把它们两个都改成有序字典。

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
}

编辑

如果您不想重写函数,也可以在脚本中心找到ConvertTo-OrderedDictionary脚本,它允许您将哈希表和数组转换为有序字典。


这太完美了。我在我的函数中漏掉了另一个 $ini[$section]。现在一切都完美无缺。 - Webtron
太棒了,@StephenP 抓得好! - briantist

4
我假设你正在调用Microsoft Script中心的此脚本 Get-IniContent?

该脚本返回[hashtable],在PowerShell中,[hashtable]是无序的。

您可以尝试更改Get-IniContent函数中的此行:

$ini = @{}

转换成这样:

$ini = [ordered]@{}

这可能使项目保持有序。

我尝试使用[ordered]或者在我的情况下$ini = New-Object System.Collections.Specialized.OrderedDictionary,但是顺序仍然混乱。不过我认为你在我的Get-IniContent函数中可能有所发现。 - Webtron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接