Forum Discussion
Remove characters from a file name
Hi everyone
I have a bunch of CSV files in a folder that need to be cleaned up. Both the file name and file contents have unneeded apostrophes. I need the apostrophes removed from the file name only. Leave contents untouched. For example,
c/test/samp'le.csv becomes c/test/sample.csv.
c:/test/Ol' Home.csv becomes c:/test/Ol Home.csv
The script needs to look at each file in a given folder and remove the apostrophe if it finds one. Not every filename will have an apostrophe in it. The apostrophe can be anywhere in the name (beginning, end, middle of filename). How would I do this in Powershell?
Thank you
Hi manny213 ,
A simple one-liner can handle this.
Get-ChildItem -Path "D:\Data\Temp\Forum" | ForEach-Object { Rename-Item -Path $_.FullName -NewName "$($_.Name.Replace("'", ''))"; }
Example
Cheers,
Lain
- LainRobertsonSilver Contributor
Hi manny213 ,
A simple one-liner can handle this.
Get-ChildItem -Path "D:\Data\Temp\Forum" | ForEach-Object { Rename-Item -Path $_.FullName -NewName "$($_.Name.Replace("'", ''))"; }
Example
Cheers,
Lain- manny213Copper Contributor
Hi LainRobertson. Thanks for the prompt reply. I am getting an error. Do you know how to fix this?
Rename-Item : Cannot create a file when that file already exists. At C:\Users\Me\Documents\Trading\SSIS\Powershell\RemoveApostropheInFilenamesScript.ps1:1 char:104 + ... ch-Object { Rename-Item -Path $_.FullName -NewName "$($_.Name.Replace ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (C:\Users\Me...Ord Shs (D).csv:String) [Rename-Item], IOException + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
- LainRobertsonSilver Contributor
Hi manny213 ,
The error's fairly straightforward.
During a Rename-Item action, a file with the proposed "new name" already exists, meaning the existing file that Rename-Item is working on cannot be renamed.
Here's an example where the file named "forum'.ps1" cannot be renamed as another file named "forum.ps1" already exists.
Cheers,
Lain