Brian Jones
Brian Jones

Reputation: 33

how to have powershell script search through directories along with root directory

cd ("F:\Offcloud\Gossip Girl\Season 01")
Dir | Rename-Item -NewName { $_.Name -replace "%20","" }
Dir | Rename-Item -NewName { $_.Name -replace "%27","" }
Dir | Rename-Item -NewName { $_.Name -replace "a","" }
Dir | Rename-Item -NewName { $_.Name -replace "b","" }
Dir | Rename-Item -NewName { $_.Name -replace "c","" }
Dir | Rename-Item -NewName { $_.Name -replace "d","" }
Dir | Rename-Item -NewName { $_.Name -replace "e","" }
Dir | Rename-Item -NewName { $_.Name -replace "f","" }
Dir | Rename-Item -NewName { $_.Name -replace "g","" }

Etc.. basically, I want to remove everything except a small list (0123456789x). Is there any way I can do this? My current script is taking a very LONG time. Also, how can I change my script to also go through all children directories?

Upvotes: 1

Views: 138

Answers (2)

Richard
Richard

Reputation: 7000

You can use the -Recurse parameter to search down directory levels.

$SearchFolder = "F:\Offcloud\Gossip Girl\Season 01"
Get-ChildItem -Path $SearchFolder -Recurse `
    | Rename-Item -NewName { 
        ($_.BaseName -replace "%20|%27|a|b|c|d|e|f|g","") + $_.Extension 
    }

Then if you use the regex's OR operator (|) in your -replace string you can replace all strings at once. The replace is done on the BaseName which is the file name without the extension. Then we simply add the extension onto the end.

Upvotes: 1

saftargholi
saftargholi

Reputation: 980

use this command :

$path = "F:\Offcloud\Gossip Girl\Season 01"

dir $path -Recurse -Include * |Rename-Item -NewName { $_.Name -replace "%20|%27|a|b|c|d|e|f|g|h","" }

Upvotes: 0

Related Questions