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
相关产品推荐
相关产品推荐

