循环.txt文件并将其转换为.csv文件。拉链呢?

时间:2022-10-29 16:05:18

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?

我有3个.txt文件,我需要转换为.csv。以下似乎有效,但我想知道是否有更清洁/更有效的方法来做到这一点?

$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.

我还需要压缩这3个.csv文件,但我不知道如何使用我当前的实现。我是否应该在创建这些新的.csv文件时将它们放入数组中然后压缩数组?任何建议都非常感谢。

1 个解决方案

#1


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.

请注意,我更改了$ filePath的定义方式。

#1


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.

请注意,我更改了$ filePath的定义方式。