Powershell:将文本文件转换为csv文件

时间:2013-09-27 13:43:14

标签: python powershell csv

$SearchFolder = "C:\Test\New folder\*.txt" 


$CSVFilePath = "C:\Test\txtfiles" # this doesn't work... 


$File = Select-String -Path $SearchFolder -Pattern new-print-server, default, dymo, zebra -NotMatch | select line, filename



$File | foreach-object {
$_.line = $_.line.replace("^",",")

}


$File | export-csv -path $CSVFilePath -NoTypeInformation


$csv = Get-Content -path $CSVFilePath



$csv | Out-File $CSVFilePath -Encoding utf8


Invoke-Item $CSVFilePath

这是我从网上获得的一个脚本,我想将文本文件夹转换为csv文件。 此代码仅允许我将所有txt文件放入一个csv文件中。 我想将多个txt文件转换为多个具有相同名称的csv文件。

1 个答案:

答案 0 :(得分:2)

对于Select-String,您需要引用Pattern例如:

Select-String -Path $SearchFolder -Pattern 'new-print-server, default, dymo, zebra' -NotMatch | select line, filename

看看这是否让你更接近:

$files = Get-ChildItem "C:\Test\New folder\*.txt"
foreach ($file in $files) {
    $notMatchedLines = $file | Select-String -Pattern 'new-print-server, default, dymo, zebra' -NotMatch | select line,filename
    $notMatchedLines | foreach {$_.line = $_.line.replace("^",",")}
    $notMatchedLines | Export-Csv ([io.path]::ChangeExtension($file.Fullname, '.csv')) -NoTypeInformation -Encoding UTF8
}