How to Perform a Replace of Specific Character on a File Name?


I have a issue where I would like to change file extensions in bulk from a network share or a user's H:\ drive. The user's H:\ drive is full of many files that are original been appended with a ".tmp" or "~#######.tmp". This has occurred after moving files from one location to another or during a backup procedure. 

The user will see something of this example: "OriginalDocumentName.docx.tmp" or "OriginalPresentation.pptx~RF4b74g32.TMP"

I am trying to create a PowerShell script that will help me rename all the files within the directory recursively by removing the .tmp or ~####.TMP from the end of those files.

I have created the following PowerShell script but not understanding why it isn't working, even after reading the documentation and from what I could understand from it, I have not been able to resolve this issue.



$Directory = "C:\Temp\Test_Rename_Test"

$FileVar = Get-ChildItem -Path $Directory -Recurse -File

$FileVar.Count # see the number of files


ForEach ($Item in $FileVar) {

If ($Item.Name -contains "~") {

Rename-Item -NewName {$_.Name -replace "~.*",""} # trying to use regex here

} #End of If

ElseIf ((!$Item.Name -contains "~") -and ($Item.Extension -match ".tmp")) {Rename-Item -NewName {$_.Extension -replace ".tmp",""}}

} #End of ForEach

$FileVar.Count # see the number of files

Write-Host "`nScript Complete" -ForegroundColor Yellow


What Am I doing wrong?

Parents Reply Children