简体   繁体   中英

Powershell: Convert text files to csv files

$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

This is a script I got from online and I would like to convert a folder of text files to csv files. This code only allows me to put all the txt files into one csv files. I would like to convert multiple txt files to multiple csv files with the same names.

For Select-String you need to quote the Pattern eg:

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

See if this gets you closer:

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

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