简体   繁体   中英

How To Rename File Extension Using Powershell Set-Content

I have the following Powershell code where I intend to scan a folder for new files that are dropped into as .TXT files, replace commas with | (the pipe symbol), remove double quotes from the file and rename the file from .TXT to .CSV and save it to an output folder.

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

}

The issue I am stumped by is that the Set-Content outputs the file with the ".CSV" extension appended to the ".TXT" similar to as follows: "myfile.TXT.CSV".

How could I do what I am trying to do and also output the new file as .CSV extension without the original .TXT extension?

try this:

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

I determine the new file Path using two steps:

  1. Retrieve the file name without extension (using [io.path]::GetFileNameWithoutExtension ) and add ".csv" to it using a format string
  2. Join the directory with the new filename

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