Forum Discussion
Remove characters from a file name
- Nov 08, 2024
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
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
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
- manny213Nov 09, 2024Brass Contributor
I deleted all the source files and started over. Looks like the script ran b/c I can see the apostrophes gone. Now, I am getting a new error:
Rename-Item : The process cannot access the file because it is being used by another process. 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...eries A (D).csv:String) [Rename-Item], IOException + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
Do you know how to fix this one?
Thank you
- LainRobertsonNov 09, 2024Silver Contributor
Hi manny213 ,
The error is telling you that a file, for which we can only see the partial path of "C:\Users\Me...eries A (D).csv", is in use by another process. You cannot rename a file (most of the time) when it's being used by another process.
There are ways of finding which process has a lock on a file, however, none of them are short explanations. Given the error is referring to a CSV file, I'd be inclined to ensure you have closed all instances of applications like Excel, though it could be anything from a system process to a scheduled task that has a lock on the file.
Cheers,
Lain- three3fNov 09, 2024Copper Contributor
ok