简体   繁体   中英

Loop through .txt files and convert them to .csv files. Then zip them?

I've got 3 .txt files that I need to convert to .csv . The below seems to work, but I was wondering if there is a cleaner/more efficient way to do this?

$files = @("C:\AllAcctsLog.txt", "C:\WithAcctsLog.txt", "C:\WithoutAcctsLog.txt")

foreach($file in $files){
    $filePath = Join-Path ([System.IO.FileInfo]$file).DirectoryName ([System.IO.FileInfo]$file).BaseName
    Import-Csv $file -Delimiter ';' -Header (1..12) | 
    ConvertTo-Csv -NoTypeInformation | select -Skip 1 |
    Set-Content ($filePath + '.csv')
}

I also need to zip these 3 .csv files, but I'm not sure how to do that with my current implementation. Should I be placing these new .csv files into an array as they're created and then zip the array? Any suggestions are greatly appreciated.

I would probably do something like this:

$files = @("C:\AllAcctsLog.txt", "C:\WithAcctsLog.txt", "C:\WithoutAcctsLog.txt");

$outputFiles = @();
$archiveName = '"C:\archive.zip"';
$7Zip = 'C:\Program Files\7-Zip\7z.exe';

foreach($file in $files){
    $filePath = Join-Path ([System.IO.FileInfo]$file).DirectoryName (([System.IO.FileInfo]$file).BaseName + '.csv');
    $outputFiles += "`"$filePath`"";
    Import-Csv $file -Delimiter ';' -Header (1..12) | 
    ConvertTo-Csv -NoTypeInformation | select -Skip 1 |
    Set-Content $filePath;
}

$outputFiles = $outputFiles -join ' ';

&$7Zip a $archiveName $outputFiles

Note that I changed how $filePath is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM