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

Hello,

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.

Sources: 

https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-6 

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/rename-item?view=powershell-6

------------------------------------------------------------------------------------------------------------------------------------

$Directory = "C:\Temp\Test_Rename_Test"

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

$FileVar.Count # see the number of files

$FileVar

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
No Data