Search code examples
powershellforeachwhile-loopfile-get-contentsforeach-object

check names in a folder and delete double quotes in a csv using a powershell loop


I'm trying to loop on files in a specific folder and delete double quotes in them

anyone could explain this ,I did this :

Get-ChildItem "c:\temp\test\" -filter SplitCSV* | 

    ForEach-Object {
    (Get-Content $_) -replace '(?m)"([^,]*?)"(?=,|$)', '$1' | Set-Content $_   }

With this error message :

Get-Content : Impossible de trouver le chemin d'accès «
C:\Users\cptspinstalldev\SplitCSV_03-08-2020_9.csv», car il n'existe pas.

So I moved my files in C:\Users\cptspinstalldev\ and it worked but why did my get-childitems didn't look in the right folder which is c:\temp\test\

Looks like I was not in the right folder so dumb


Solution

  • As it is unsafe to delete all quotes in existing CSV files, please consider using my function ConvertTo-CsvNoQuotes to do that for you.

    Add the function on top of your script and do:

    Get-ChildItem -Path "c:\temp\test" -Filter 'SplitCSV*.csv' -File | 
        ForEach-Object {
            (Import-Csv -Path $_.FullName) | ConvertTo-CsvNoQuotes | Set-Content $_.FullName
        }
    

    If you're on PowerShell 7.0, you can do without that function and simply code as

    Get-ChildItem -Path "c:\temp\test" -Filter 'SplitCSV*.csv' -File | 
        ForEach-Object {
            $file = $_.FullName
            (Import-Csv -Path $file) | Export-Csv -Path $file -UseQuotes AsNeeded
        }