Web*_*ron 2 powershell foreach
我正在使用PowerShell的配置文件,并且每次调用foreach循环来捕获数据时,它都会以错误的顺序捕获数据。见下文:
config.ini
[queries]
query01=stuff1
query02=stuff2
query03=stuff3
query04=stuff4
Run Code Online (Sandbox Code Playgroud)
该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
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
stuff1
stuff4
stuff2
stuff3
Run Code Online (Sandbox Code Playgroud)
我假定这与PowerShell中的异步处理有关,但是config.ini按我将文件存储在其中的顺序来处理文件查询的最佳方法是什么?
注意:我将数字添加到查询(query01)的末尾只是出于测试目的。这些查询将不在我的final中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
}
Run Code Online (Sandbox Code Playgroud)
您需要将两个哈希表声明都更改为有序字典。如果你只改变
$ini = @{}
Run Code Online (Sandbox Code Playgroud)
至
$ini = [ordered]@{}
Run Code Online (Sandbox Code Playgroud)
您的$ ini现在是有序词典,但在创建的嵌套哈希表
$ini[$section] = @{}
Run Code Online (Sandbox Code Playgroud)
仍然是无序哈希表。您需要将它们都更改为有序词典。
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
}
Run Code Online (Sandbox Code Playgroud)
编辑
脚本中心上还有一个ConvertTo-OrderedDictionary脚本,如果您不想重写函数,该脚本可让您将哈希表和数组转换为有序字典。
| 归档时间: |
|
| 查看次数: |
2261 次 |
| 最近记录: |