1

I am using a program to export hundreds of rows in an Excel sheet into separate documents, but the problem is that a PLC will be reading the files and they only save in (macintosh).csv with no option for windows. Is there a way to bulk convert multiple files with different names into the correct format?

I have used this code for a single file but I do not have the knowledge to use it for multiple in a directory

$path = 'c:\filename.csv';
[System.IO.File]::WriteAllText($path.Remove($path.Length-3)+'txt',[System.IO.File]::ReadAllText($path).Replace("`n","`r`n"));

Thank you

noksnero
  • 21
  • 3

1 Answers1

1

The general PowerShell idiom for processing multiple files one by one:

Specifically, since you're calling .NET API methods, be sure to pass full, file-system-native file paths to them, because .NET's working directory usually differs from PowerShell's. $_.FullName does that.

Therefore:

Get-ChildItem -LiteralPath C:\ -Filter *.csv |
  ForEach-Object {
    [IO.File]::WriteAllText(
      [IO.Path]::ChangeExtension($_.FullName, 'txt'),
      [IO.File]::ReadAllText($_.FullName).Replace("`n", "`r`n")
    )
  }

Note:

  • In PowerShell type literals such as [System.IO.File], the System. part is optional and can be omitted, as shown above.

  • [System.IO.Path]::ChangeExtension(), as used above, is a more robust way to obtain a copy of a path with the original file-name extension changed to a given one.

  • While Get-ChildItem -Path C:\*.csv or even Get-ChildItem C:\*.csv would work too (Get-ChildItem's first positional parameter is -Path), -Filter, as shown above, is usually preferable for performance reasons.

    • Caveat: While -Filter is typically sufficient, it does not use PowerShell's wildcard language, but delegates matching to the host platform's file-system APIs. This means that range or character-set expressions such as [0-9] and [fg] are not supported, and, on Windows, several legacy quirks affect the matching behavior - see this answer for more information.
mklement0
  • 382,024
  • 64
  • 607
  • 775