Powershell script to rename files

I have a bunch of files with names that start with numbers, can contain spaces and dashes after one of the two numbers, and sometimes (sometimes not) have a space immediately before the first alpha character of the name that I want to save, i.e.:

2-01 Dazed And Confused.txt (I want to rename it to Dazed And Confused.txt)

or

02 - Uncle Salty.txt (I want to rename this to Uncle Salty .txt)

Or

02-Night Before.txt (I want to rename The Night Before.txt)

+4
source share
3 answers
dir c:\tmp | % { mv $_.FullName $(Join-Path $_.Directory ($_.Name -replace "^([0-9\-\s]*)",'').Trim()); } 

If you need to recursively process your directory, add -recurse after dir .

+4
source

Move-Item and Rename-Item cmdlets can take a source directly from the pipeline and provide a new name using a script block:

 dir | Move-Item -Destination { $_.Name -replace '^([0-9\-\s]*)' } 

or

 dir | Rename-Item -NewName { $_.Name -replace '^([0-9\-\s]*)' } 
+6
source

Try something like this:

 $re = '^\d+\s*-\d*\s*(.*)$' $recurse = $false Get-ChildItem "C:\some\folder" -Recurse:$recurse | ? { -not $_.PSIsContainer -and $_.Name -match $re } | % { Move-Item $_.FullName (Join-Path $_.Directory $matches[1]) } 

If you want the hyphen to be optional, change the regular expression to '^\d+\s*-?\d*\s*(.*)$' .

If you want to rewrite to subfolders, change $recurse to $true .

0
source

All Articles