PowerShell foreach 没有正确迭代

问题描述

我有一些 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' 似乎没有正常工作,因为它没有将键/值对放入哈希表中。我想让它工作,以便 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}