1

I am trying to replace null values in a certain column to 0 using PowerShell.

I have the CSV in this format:

test   test2    test3    test4
----   -----    -----    -----
blah   fsds       4      45645
bla1   fsds1             45645
blah2  fsds2      4      34322
blah3  fsds3      4      67544
blah4  fsds4             3432432

so I want to go through the null values in "test3" and replace to 0.

I have this, but it doesn't work:

$inFilePath = "G:\powershell\excel\test.csv"
$csvColumnNames = (Get-Content $inFilePath | Select-Object -First 1).Split(",")

foreach ($row in $inFilePath) {
    if ($row.test3 -eq $null) {
        $row.test3 = 0
        Write-Host "updating value in excel"
    }
}

$csvColumnNames | Export-Csv  "G:\powershell\excel\replaced2.csv" -NoTypeInformation

2 Answers 2

1

you are on the right track with foreach and if.Try this:

foreach($row in $inFilePath)
{
    if (-not $row.test3)
    {
      $row.test3= 0
    }

}

to get the column headers:

$inFilePath | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
Sign up to request clarification or add additional context in comments.

4 Comments

hey that works as expected. but would you have a format thats less powershelly? I want it in a format where I can do a few other checks before it enters the foreach-object.
can you elaborate a little more on what you mean by 'less powershelly'
as in one that doesnt use " |" so i can do further checked after importing and before the foreach-object loop?. E.g. I need this link in there $csvColumnNames = (Get-Content $inFilePath | Select-Object -First 1).Split(",")
you can put whatever code you wanted inside the foreach-object but to keep things simple you can re-use the original code you posted. I guess the only thing you needed to change was $row.test3 -eq $null
1

Use Import-Csv for reading and Export-Csv for writing CSV files.

$inFilePath  = "G:\powershell\excel\test.csv"
$outFilePath = "G:\powershell\excel\replaced2.csv"

Import-Csv $inFilePath | % {
  if (-not $_.test3) { $_.test3 = 0 }
  $_   # echo all records, so they can be exported back to a file
} | Export-Csv $outFilePath -NoType

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.