如何使用Powershell Set-Content重命名文件扩展名

时间:2015-03-24 09:40:13

标签: powershell csv batch-processing powershell-v3.0 file-extension

我有以下Powershell代码,我打算在文件夹中扫描以.TXT文件形式删除的新文件,用逗号替换逗号。 (管道符号),从文件中删除双引号,并将文件从.TXT重命名为.CSV并将其保存到输出文件夹。

param($InputDIR,$OutputDIR)

$Dir = get-childitem $InputDIR -Recurse

$CSVList = $Dir | where {$_.Name -like "*.TXT"}
Write-Host -ForegroundColor White -BackgroundColor Blue "Scanning For Input Files In $InputDIR"
Foreach ($csvfile in $CSVList )
{
#ASSIGN THE CSV FILE INTO A VARIABLE.
$CSVFullFileName = $csvfile.FullName
$CSVFileName = $csvfile.Name
$InputFile = (Join-Path $InputDIR $CSVFileName)

Get-Content $InputFile | ForEach-Object { $_ -replace ",", "|" } | ForEach-Object { $_ -replace """", "" } | Set-Content ($InputFile+".csv")

Write-Host -ForegroundColor White -BackgroundColor Blue "Working on $CSVFileName"
Write-Host -ForegroundColor White -BackgroundColor Blue "Object Scan: $_"
#Remove-Item $InputFile
#Rename-Item ($InputFile+".csv") $InputFile

}

我感到困惑的是,Set-Content输出的文件的“.CSV”扩展名附加在“.TXT”上,类似如下:“myfile.TXT.CSV”。

我怎么能做我想做的事情,并且还将新文件作为.CSV扩展名输出而没有原始.TXT扩展名?

1 个答案:

答案 0 :(得分:2)

试试这个:

param($InputDIR,$OutputDIR)

$Dir = get-childitem $InputDIR -Recurse

$CSVList = $Dir | where {$_.Name -like "*.TXT"}
Write-Host -ForegroundColor White -BackgroundColor Blue "Scanning For Input Files In $InputDIR"
Foreach ($csvfile in $CSVList )
{
#ASSIGN THE CSV FILE INTO A VARIABLE.
$CSVFullFileName = $csvfile.FullName
$CSVFileName = $csvfile.Name
$InputFile = (Join-Path $InputDIR $CSVFileName)
$newFileName = "{0}.csv" -f ([io.path]::GetFileNameWithoutExtension($CSVFileName))
$newFilePath = (Join-Path $InputDIR $newFileName)

Get-Content $InputFile | ForEach-Object { $_ -replace ",", "|" } | ForEach-Object { $_ -replace """", "" } | Set-Content $newFilePath

Write-Host -ForegroundColor White -BackgroundColor Blue "Working on $CSVFileName"
Write-Host -ForegroundColor White -BackgroundColor Blue "Object Scan: $_"
#Remove-Item $InputFile
#Rename-Item ($InputFile+".csv") $InputFile

我使用两个步骤确定新文件Path:

  1. 检索没有扩展名的文件名(使用 [io.path] :: GetFileNameWithoutExtension )并使用格式字符串添加“.csv”
  2. 使用新文件名
  3. 加入目录