如何在不知道列名的情况下一一更新csv中的单元格

How to update cells in csv one by one without knowing column names

我尝试替换 csv 中的一些文本,如下所示:

$csv = Import-Csv $csvFileName -Delimiter ';'
foreach ($line in $csv)
{
    $properties = $line | Get-Member -MemberType Properties
    for ($i = 0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $value = $line | Select -ExpandProperty $column.Name
        
        # Convert numbers with , as separator to . separator
        if ($value -match "^[+-]?(\d*\,)?\d+$")
        {
            $value = $value -replace ",", "."
            # HOW TO update the CSV cell with the new value here???
            # ???
        }
    }
}
$csv | Export-Csv $csvFileName -Delimiter ',' -NoTypeInformation -Encoding UTF8

如您所见,我错过了要用新值更新 csv 行的单元格值的行 => 谁能告诉我该怎么做?

假设您的正则表达式与您期望的模式匹配,您可以使用 2 个 foreach 循环简化代码,这比 for 更容易。此方法调用内部 PSObject 成员,可用于所有 PowerShell 对象。

$csv = Import-Csv $csvFileName -Delimiter ';'

foreach ($line in $csv) {
    foreach($property in $line.PSObject.Properties) {
        if ($property.Value -match "^[+-]?(\d*\,)?\d+$") {
            # regex operator not needed in this case
            $property.Value = $property.Value.Replace(",", ".")
        }
    }
}

$csv | Export-Csv ....

您也可以在管道中完成所有过程(上面的方法显然更快,但是这种方法可能对内存更友好):

Import-Csv $csvFileName -Delimiter ';' | ForEach-Object {
    foreach($property in $_.PSObject.Properties) {
        if ($property.Value -match "^[+-]?(\d*\,)?\d+$") {
            # regex operator not needed in this case
            $property.Value = $property.Value.Replace(",", ".")
        }
    }
    $_ # => output this object
} | Export-Csv myexport.csv -NoTypeInformation