I'm rather new to powershell, and I have been trying to make a script that takes all files in a directory with numbers in the title and renames them according to a template.
My Script looks like such:
$NewObjName = "My New Name"
cd E:\Test
dir | ren -NewName {$_.name -replace '([a-zA-Z])([a-zA-Z])\.(\d?)(\d).*','0$3$4'}
dir | ren -NewName {$_.name -replace '(\d?)(\d)(\d)',{Part $2$3 $NewObjName.txt}}
and does this:
PS E:\Test> ls
Directory: E:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 8/1/2022 2:14 PM 0 AB.01CDE
-a---- 8/1/2022 2:15 PM 0 AB.02CDE
-a---- 8/1/2022 2:15 PM 0 AB.10CDE
-a---- 8/1/2022 2:15 PM 0 AB.11CDE
PS E:\Test> E:\RenameScript.ps1
PS E:\Test> ls
Directory: E:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 8/1/2022 2:14 PM 0 Part 01 $NewObjName.txt
-a---- 8/1/2022 2:15 PM 0 Part 02 $NewObjName.txt
-a---- 8/1/2022 2:15 PM 0 Part 10 $NewObjName.txt
-a---- 8/1/2022 2:15 PM 0 Part 11 $NewObjName.txt
PS E:\Test>
So it just puts in the variable name instead of the value of the variable.
I'm not sure if -replace
doesn't allow variables other than regex groupings or if I'm just missing something?
Thanks in advance :)
Edit: My expected result would be something like:
PS E:\Test> ls
Directory: E:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 8/1/2022 2:14 PM 0 Part 01 My New Name.txt
-a---- 8/1/2022 2:15 PM 0 Part 02 My New Name.txt
-a---- 8/1/2022 2:15 PM 0 Part 10 My New Name.txt
-a---- 8/1/2022 2:15 PM 0 Part 11 My New Name.txt