You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell Foreach循环问题:CSV新增列赋值错误求助

解决CSV新增列每行赋值错误的问题

你的问题出在foreach循环里,所有行都被统一赋值了$Newvalue1,没有区分行的位置。可以通过以下两种方式修正:

方法1:使用索引遍历数组

利用Import-Csv返回结果为数组的特性,用for循环根据索引给每行分配对应的值:

# Set the path to the existing CSV file
$csvPath = "C:\path\to\existing\file.csv"

# Import the CSV file
$data = Import-Csv -Path $csvPath

# Get today's date in the desired format for the new column name
$newColumnName = Get-Date -Format "yyyy-MM-dd"

# 将目标值存入数组,索引对应行号(从0开始)
$newValues = @("100", "200")

# 通过索引遍历每行,分配对应值
for ($i = 0; $i -lt $data.Count; $i++) {
    $data[$i] | Add-Member -MemberType NoteProperty -Name $newColumnName -Value $newValues[$i]
}

# Export the updated data to the CSV file
$data | Export-Csv -Path $csvPath -NoTypeInformation

方法2:在foreach中记录行号

如果习惯使用foreach,可以初始化计数器,遍历过程中递增计数器,根据计数器值选择对应的值:

# Set the path to the existing CSV file
$csvPath = "C:\path\to\existing\file.csv"

# Import the CSV file
$data = Import-Csv -Path $csvPath

# Get today's date in the desired format for the new column name
$newColumnName = Get-Date -Format "yyyy-MM-dd"

$Newvalue1 = "100"
$Newvalue2 = "200"
$rowIndex = 0

foreach ($row in $data) {
    # 根据行索引选择对应值
    $value = if ($rowIndex -eq 0) { $Newvalue1 } else { $Newvalue2 }
    $row | Add-Member -MemberType NoteProperty -Name $newColumnName -Value $value
    $rowIndex++
}

# Export the updated data to the CSV file
$data | Export-Csv -Path $csvPath -NoTypeInformation

说明:两种方法都能实现第一行赋值100、第二行赋值200的需求。如果后续行数增加,方法1只需扩展$newValues数组即可,灵活性更高。

内容的提问来源于stack exchange,提问作者PowerShellWiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:17:28