0

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

2 Answers2

0

In Powershell the Get-Content and Set-Content functions expect a full path. The $_ variable is a FileInfo or DirectoryInfo object. Try to pass in the full path using $_.FullName, like this:

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

ForEach-Object {
(Get-Content $_.FullName) -replace '(?m)"([^,]*?)"(?=,|$)', '$1' | Set-Content $_.FullName   }
Bart
  • 355
  • 4
  • 7
  • Your description _The $_ variable contains only the file name (without directory)_ is wrong. The `$_` automatic variable inside the loop represents either a `FileInfo` or a `DirectoryInfo` **object**. Because this is an object, it has properties like `FullName` etc. – Theo Aug 03 '20 at 14:58
0

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
    }
Theo
  • 57,719
  • 8
  • 24
  • 41