使用 Import-CSV 的 Powershell 奇怪行为

Powershell Strange behaviour with Import-CSV

我有以下 powershell 代码:

clear;
$importedIDs = (Import-Csv "testing.csv" -Delimiter ';').id;

Write-Host $importedIDs.Length;

for ($i=0; $i -lt $importedIDs.Length; $i++) {
  Write-Host $($importedIDs[$i]);
}

目标是只读取 csv 文件中的 id 列,如下所示:

"created";"id"
"2018-04-04 21:03:01";"123456"
"2018-04-04 21:03:01";"123457"

当有两行或更多行时,输出符合预期:

2
123456
123457

然而,当 csv 文件中只有 1 行(id 为 123456 的行)时,输出为:

6
1
2
3
4
5
6

期望的输出是:

1
123456

谁能解释为什么会这样,我该如何解决? 感谢任何帮助

如果 csv 中有多行,您将得到一个字符串数组。每行一个数组元素。因此索引适用于行。如果只有一行,则不会像您预期的那样得到一个包含一个字符串的数组。你得到一个字符串。在字符串上使用索引时,powershell 将字符串视为字符数组,因此 returns 只有一个字符。

您可以稍微重写脚本以解决 J. Bergmann 描述的问题。

不是使用 for 循环遍历数组中的每个元素,其中 "element" 可能引用字符串数组中的字符串或字符串中的字符,您可以使用foreach 循环并遍历数组中的元素,如下所示。 foreach 不会将字符串视为字符数组

clear;
$importedIDs = (Import-Csv "testing.csv" -Delimiter ';').id;

Write-Host $importedIDs.Length;

foreach ($importedID in $importedIDs) {
  Write-Host $($importedID);
}