0

Delete empty rows in Multiple CSV files in a Folder by using PowerShell

This is the code I am trying, But it is writing empty files. Not Sure What's wrong with this code. Any suggestions would be appreciated. thank you.

$dest= "C:\Test"
Get-ChildItem $dest *.csv | ForEach-Object {
Get-Content $_.FullName | Where { $_.Replace(",","").trim() -ne "" }  | Out-File $_.FullName
}
0

1 Answer 1

1

This behavior is expected, Get-Content and Out-File should not be sharing the same pipeline if reading and writing to the same file. Either, surround Get-Content with brackets or store the content in a variable and then write the file.

$dest = "C:\Test"
Get-ChildItem $dest *.csv | ForEach-Object {
    (Get-Content $_.FullName) | Where { $_.Replace(",","").trim() -ne "" } |
    Out-File $_.FullName
}

# OR

$dest = "C:\Test"
Get-ChildItem $dest *.csv | ForEach-Object {
    (Get-Content $_.FullName | Where { $_.Replace(",","").trim() -ne "" }) |
    Out-File $_.FullName
}

# OR

$dest = "C:\Test"
Get-ChildItem $dest *.csv | ForEach-Object {
    $content = Get-Content $_.FullName | Where { $_.Replace(",","").trim() -ne "" }
    Out-File -InputObject $content -FilePath $_.FullName
}
Sign up to request clarification or add additional context in comments.

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.