Search code examples
powershellcsvjoinsplit

Powershell - I am unable to match a string in an if statement even if I use -contains instead of -eq


I have a .csv file that I need to change a field based on the value of another field. The important part of the data is: "08-01-2023 09:00:00","08-02-2023 09:00:00","937600","Sonat Measurement",...

I want to change the "Sonat Measurement" field value in each row based on what we have in the previous field.

    $data = Get-Content $AFw
    Foreach ($row in $data){
        $values = $row -split ','
        Write-Host $values[2]
        Write-host $values[3]
        if ($values[2] -contains 937600){
            $values[3] = "SNG TRUMBOWER NASSAU"
            } elseif ($values[2] -contains 937700){
                $values[3] = "SNG NORMANDY  DUVALL"
                } elseif ($values[2] -contains 960530){
                    $values[3] = "SNG JACKSONVILLE NASSAU"
                    } elseif ($values[2] -contains 960590){
                        $values[3] = "SNG BAKER NASSAU"
                        } elseif ($values[2] -contains 96108){
                            $values[3] = "WILDWOOD"
                            } elseif ($values[2] -contains 10){
                                $values[3] = "DRAINFIELD"
                                }

        $newRow = $values -join ','
        $data = $data -replace [regex]::Escape($row), $newRow

    }

I have tried -eq, -contains, all versions of quotes "", '' without quotes, etc. I havent even gotten to the join portion of the code. Write-host $value[2] prints out "937600" Write-host $value[3] prints out "Sonat Measurement"


Solution

  • You can use regex and replace all the data. May not be the most efficient way, but hope this helps.

    # Create matching pattern
    $findPattern = '"{pattern}","Sonat Measurement"'
    
    # Create replacement pattern
    $replacePattern = '"{pattern}","{newMeasurement}"'
    
    # Create an array of replacements. if you need a bunch, get them from a file. This has two hardcoded elements.
    $replacements = @(
        [PSCustomObject]@{
            value = "937600"
            newMeasurement = "SNG TRUMBOWER NASSAU"
        },
        [PSCustomObject]@{
        value = "937700"
        newMeasurement = "SNG NORMANDY DUVALL"
        }
    )
    
    # Read the data from the file.
    $data = Get-Content "C:\Projects\PSTests\data.txt" -Raw
    
    # loop through the replacement array replacing all values in the file.
    foreach($replacement in $replacements)
    {
        $fpattern = $findPattern.Replace("{pattern}",$replacement.value)
        $rpattern = $replacePattern.`
            Replace("{pattern}",$replacement.value). `
            Replace("{newMeasurement}",$replacement.newMeasurement)  
        $data = $data -Replace $fpattern, $rpattern
    }
    
    # put data out to a file     
    $data | out-file -FilePath "C:\Projects\PSTests\newdata.txt"