I'm having quite a bit of trouble making a rename-script in PowerShell. The situation: In a directory I have folders named with the following format: "four digits - text - junk" Which I want to rename to "text (four digits)"
Right now I have created a directory with some sample names to play around with:
1996 - something interesting - something crappy
2006 - copy this - ignore
I've tried setting up a script to echo their names to begin with but I can't quite get the hang of the regex. The following code just prints "1996 - something" and "2006 - copy"
Get-ChildItem | Foreach-Object { if ($_.BaseName -match "(\d{4} - \w+ -*)") { echo $matches[0]}}
and this one will print "1996 - something interesting - something crappy \n ()" and "2006 - copy this - ignore\n ()"
Get-ChildItem | Foreach-Object { echo ($_.BaseName -replace "(\d{4} - \w+ - *)"), "$2 ($1)"}
Can someone tell me why neither approach respects the literal string " - " as a boundary for the matching?
*EDIT* Thanks zespri, the code that solved my problem is
Get-ChildItem | Foreach-Object {
if ($_.BaseName -match "(\d{4} - [^-]*)") {
Rename-Item $_ ($_.BaseName -replace "(\d{4}) - (.+)(?= -).*" ,'$2 ($1)')
}
}