数组第一个元素

Array first element

我正在尝试拆分从 csv 文件中读取的数组,但除了第一个数组元素外,我无法捕获任何内容。这是我的代码

$EmployeeLists = @()
$ManagerLists = @()

$CSVFiles = Import-CSV "C:\T2\SetManagers\EmployeeManager.csv"

ForEach($CSVFile in $CSVFiles) { $EmployeeLists += ($CSVFile.Employee) }
ForEach($CSVFile in $CSVFiles) { $ManagerLists += ($CSVFile.Manager) }

ForEach($EmployeeList in $EmployeeLists) { $EmployeeLists.Split(",")[0] | Out-File "C:\T2\SetManagers\ESplit.txt" -Append }
ForEach($ManagerList in $ManagerLists) { $ManagerLists.Split(",")[0] | Out-File "C:\T2\SetManagers\MSplit.txt" -Append }

我的看跌期权看起来像这样

Smith
Smith
Smith
Smith
Smith
Smith
Smith

正确的格式大有帮助:

$csv = Import-Csv -Path C:\T2\SetManagers\EmployeeManager.csv

foreach ($list in $csv) {
    $list.Employee.Split(',')[0] | Out-File -Path C:\T2\SetManagers\ESplit.txt -Append
    $list.Manager.Split(',')[0] | Out-File -Path C:\T2\SetManagers\MSplit.txt -Append
}

您的问题是指整个列表而不是 foreach 循环中的单个元素。

解释您的代码存在的问题并提供有效的解决方案。

  • 如果您对(固定的)代码的性能感到满意,并且您认为没有必要改进您的代码,这就是您所需要的。

  • 要了解可缩短和加速代码的可重用技术,请继续阅读。


简洁的 PowerShell 惯用解决方案,性能更好 (PSv4+):

# Read the CSV rows (into custom objects whose properties contain the
# column values).
$rows = Import-CSV "C:\T2\SetManagers\EmployeeManager.csv"

# Collect all Employee and Manager column values in an array each.
$employeeLists = $rows.Employee
$managerLists = $rows.Manager

# Loop over all column values, extract only the first ","-separated token each
# and send the combined output to an output file.
$employeeLists.ForEach({ ($_ -split ',')[0] }) > "C:\T2\SetManagers\ESplit.txt"
$managerLists.ForEach({ ($_ -split ',')[0] }) >  "C:\T2\SetManagers\MSplit.txt"

具体来说,上面的代码避免了:

  • 使用 += 循环 中构建数组,这需要 重新创建 数组 (在 每次迭代 .

    中附加新值)
    • 相反,它使用 member-access enumeration (PSv3+) 直接检索 属性 值的数组(例如,$employeeLists = $rows.Employee

    • 即使在 PSv2 中,相对简洁和更高效的形式也是可能的; $employeeLists = $rows.Employee 的 PSv2 等价物是:

          # *PowerShell* does the work of collecting the outputs from the individual
          # loop iterations and simply returns an array.
          $employeeLists = foreach ($row in $rows) { $row.Employee }
      
    • 最后,如果您确实需要迭代地建立一个集合并且速度很重要,请使用 可扩展 集合类型,例如 [System.Collections.Generic.List[object]] 及其 .Add() 方法,而不是具有 +=.

      的数组
  • 循环中调用Out-File,这会在每次迭代中产生 cmdlet 的启动和拆卸成本,并且还需要每次重新打开和关闭文件时间。

    • 相反,语句的 combined 输出在 single Out-File 调用中写入输出文件(缩短到 > 为简洁起见)。
  • PSv4+.ForEach()方法foreach循环表现更好(尽管只是一点点),并且具有可以直接将其用作管道的第一段的优点(而 foreach 循环需要在 $(...) 中包装)。
    在 PSv3- 中,使用 foreach 循环。