Bulk rename files / remove part of filename

<#


 AUTHOR: Rasmus Schmidt
 EMAIL: rsc@itafdelingen.dk

For bulk renaming files, creates a logfile on the script path.
Asks the user for a path to the folder containing the files and what to remove of the filename
create the log file in the same location as the script with info on the renamed files

 
#>

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
Add-Type -AssemblyName PresentationFramework
$msgBoxInput = [System.Windows.MessageBox]::Show('Warning, this script renames all files in the directories in the path you enter, Continue?','Warning','YesNoCancel','Error')

switch  ($msgBoxInput) {
'Yes' {

$filepath = [Microsoft.VisualBasic.Interaction]::InputBox("Write path to top level directory", "Filepath", "")
$removestring =[Microsoft.VisualBasic.Interaction]::InputBox("Write the part you want to remove", "Filename", "")

$path = split-path -parent $MyInvocation.MyCommand.Definition
$log = "$path\RenamedFiles.log" 
$date = Get-Date -format F
"Renamed the following files (on. " + $date + "): " | Out-File $log -append 
"--------------------------------------------" | Out-File $log -append 

$files = Get-ChildItem -Filter * $filepath -recurse | where {$_.Name -like "*$removestring*"}

foreach ($file in $files) {
      
         Rename-Item -Path $file.FullName $file.name.Replace($removestring,"") -ErrorAction Stop
         $newname = $file.name.Replace($removestring,"")
         $output = "Renaming $file to $newname"
         $output | Out-File $log -append
         }
}

'No' {
Write-host "Thank you!"
    }

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *