PowerShell foreach 没有正确迭代

PowerShell foreach not iterating correctly

我有一些 SQL 输出,我正尝试通过 PowerShell 的 foreach cmdlet 进行操作,但我 运行 遇到了让它遍历每一行输出的问题。

这是我的 PowerShell 代码:

$result = @(D:\sql_select.bat --file D:\SQL.sql)
$output = $result -split "`r`n"

foreach ($l in $output) {
$name = [Regex]::Matches($output, ".+?(?=~)")
$size = [Regex]::Matches($output, "[^~]*$")
$tables += @{$name = $size}
}

这是我正在处理的 SQL 输出的一部分:

Table1~9.00
Table2~5.61
Table3~1.13
Table4~0.93
Table5~0.72
Table6~0.57

'foreach $l in $output' 似乎没有正常工作,因为它没有将 key/value 对放入哈希表。我想让它工作,以便 Table1 将成为值为 9.00 的键,Table2 将与 5.61 配对,等等。我怎样才能让它工作?

(注意:我知道 Invoke-SQLCmd 在 PowerShell 中可用并且非常有用,但不幸的是我不能在这里使用它。所以,请不要麻烦建议作为解决方案。)

所以,我使用你的 SQL 输出作为我测试的输入,这应该可以正常工作:

$output='Table1~9.00
Table2~5.61
Table3~1.13
Table4~0.93
Table5~0.72
Table6~0.57' -split '\s+'

foreach ($l in $output) {
    $name = ([Regex]::Match($l, ".+?(?=~)")).Value
    $size = ([Regex]::Match($l, "[^~]*$")).Value
    $tables += @{$name = $size}
}

PS C:\> $tables

Name                           Value                                                                                        
----                           -----                                                                                        
Table1                         9.00                                                                                         
Table2                         5.61                                                                                         
Table3                         1.13                                                                                         
Table4                         0.93                                                                                         
Table5                         0.72                                                                                         
Table6                         0.57   

如果您使用 [regex]::Matches,您的匹配项将是一个数组,结果将如下所示:

PS C:\> $tables

Name                           Value                                                                                        
----                           -----                                                                                        
Table6                         {0.57, }                                                                                     
Table5                         {0.72, }                                                                                     
Table4                         {0.93, }                                                                                     
Table3                         {1.13, }                                                                                     
Table2                         {5.61, }                                                                                     
Table1                         {9.00, } 

如果您需要有序哈希表,您可能还需要使用 $tables += [ordered]@{$name = $size}