将多个文本文件保存到csv文件

时间:2014-01-30 22:29:37

标签: powershell

我正在编写一个脚本来格式化一个充满文本文件的目录并将它们导出为CSV文件。我希望它执行搜索并替换每个文件以正确格式化,将其导出到具有相同文件名的CSV,然后移动到下一个txt文件。我有搜索和替换工作,但无法解决如何使用其原始文件名保存每个文本文件。我究竟做错了什么?

$path = "H:\My Documents\EmailSaveAs\"
$files = Get-ChildItem -Path $path -include *.txt -recurse
echo $files
foreach($file in $files) {
    Foreach-Object {
         $_ -replace  "`r`n`t", ","  -replace  "\s`r`n", "," -replace "Bytes `r`nOut", "Bytes Out" -replace  "`t", "," -replace  "Idle-`r`ntimeout", "Idle-timeout" -replace  ",#Date", "#Date" 
        } | 
Set-Content $path $(.BaseName + ".csv")
}

1 个答案:

答案 0 :(得分:0)

试试这个:

$path = "H:\My Documents\EmailSaveAs\"
$files = Get-ChildItem $path -include *.txt -recurse
echo $files
foreach($file in $files) {
    $updatedContent = Get-Content $file.FullName -Raw | Foreach-Object {
         $_ -replace  "`r`n`t", "," -replace "\s`r`n", "," -replace "Bytes `r`nOut", "Bytes Out" -replace  "`t", "," -replace  "Idle-`r`ntimeout", "Idle-timeout" -replace ",#Date", "#Date" 
    } 
    $newFilename = [io.path]::ChangeExtension($file, ".csv")
    Set-Content $newFilename $updatedContent 
}

原始代码在管道上下文中未执行时访问$_。请注意,Get-Content上的-Raw参数在V3中是新的。