powershell

Replace "_" with " " of all files and directories within a parent directory - Powershell


I have a parent directory that contains many sub directories. I want to replace the underscore with a space in all directories and files within each directory. What's the best / quickest way to achieve this using Powershell?

E.g.

Current:

folder_1
-- file_1.mp4
-- file_1.srt
-- file_1.vtt
folder_2
-- file_2.mp4
-- file_2.srt
-- file_2.vtt
folder_3
-- file_3.mp4
-- file_3.srt
file_3.vtt

Wanted:

folder 1
-- file 1.mp4
-- file 1.srt
-- file 1.vtt
folder 2
-- file 2.mp4
-- file 2.srt
-- file 2.vtt
folder 3
-- file 3.mp4
-- file 3.srt
-- file 3.vtt

Thanks in advance!

get-childitem *.* | foreach { rename-item $_ $_.Name.Replace("_", " ") }

get-childitem -recurse | foreach { rename-item $_ $_.name.replace("_"," ") }

I have tried these but they only half do what I want.


Solution

  • Here. I split everything in 3 operations, because it's better to rename the files first and the directories second, so to not use multiple Get-ChildItem I got them all in a variable at the start.

    # Get all directories and subdirectories having a Underscore(_) in their Name.   
    $DirectoryList = Get-ChildItem -Path $BasePath -Recurse | 
        Where-Object -Property BaseName -Match '_'
    
    #Rename all files  
    $DirectoryList | Where-Object { $_.gettype().name -eq 'FileInfo' } | 
        Rename-Item -NewName { $_.Name.Replace('_', ' ') }
    
    # Rename all directories
    $DirectoryList | Where-Object { $_.gettype().name -eq 'DirectoryInfo' } |    
        # Added sort so to rename the directory recursively starting from the
        # deepest to avoid errors.  
        Sort-Object -Descending { $_.FullName.split([io.path]::DirectorySeparatorChar).count } |
        Rename-Item -NewName { $_.Name.Replace('_', ' ') }