powershell - PowerShell 中的 Foreach 循环不按顺序

标签 powershell foreach

我正在使用 PowerShell 的配置文件,每次我调用 foreach 循环来获取数据时,它都会以错误的顺序获取数据。见下文:

配置文件

[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
}

最佳答案

您需要将两个哈希表声明更改为有序字典。如果你只是改变

$ini = @{}


$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 script 允许您将哈希表和数组转换为有序字典。

关于powershell - PowerShell 中的 Foreach 循环不按顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39458677/

相关文章:

powershell - 如果您只是要编写过程代码,那么MSBUILD/NANT有什么意义? Powershell更好吗?

powershell - "You cannot call a method on a null-valued expression"在代码中使用参数时

c++ - boost::fusion::for_each 中的函数对象不同于 std::for_each

multithreading - 减少导致高CPU使用率的特定进程的线程数

forms - 在 Powershell 中检查是什么关闭了 Windows 窗体

powershell - 通过启动进程以管理员身份从 powershell 脚本重定向 stdout、stderr

asp.net-mvc-3 - 部分 View 中的表单 - 需要正确的答案

php - 使用 PHP glob 获取文件夹 - 无限深度

java - java中修改列表会影响另一个列表

java - 增强了(或 'for each' )循环迭代到它刚刚删除的元素 - 抛出错误