2014-01-30 117 views
0

我正在處理一個腳本來格式化一個包含文本文件的目錄並將其導出到CSV文件。我希望它執行搜索並替換每個文件以正確格式化,將其導出爲具有相同文件名的CSV,然後移至下一個txt文件。我有搜索和替換工作,但不能解決如何保存每個文本文件的原始文件名。我究竟做錯了什麼?將多個文本文件保存爲csv文件

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

回答

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中是新增的。

+0

輝煌 - 完美的作品!非常感謝! – Dylan

+0

或者,不是將它讀入一個變量,而是爲新名稱設置一個變量,然後設置內容,您可以將它輸出到ala'Get-Content $ file | Foreach-Object {do stuff}。 Out-File([io.path] :: ChangeExtension($ file,「.csv」))' – TheMadTechnician

+0

@TheMadTechnician這是我最初編寫它的方式,並且會在實踐中這樣做,但我想保留更多的窗口內的腳本。這樣就不需要滾動查看解決方案的有趣部分。 –