1

The script below is used for Bulk Folder Renaming.

However I wanted to make this as a Generic Script so users can give input and use it accordingly.

  1. This script has 3 inputs
    • a) Enter the Source Folder path
    • b) Extension of the Files and
    • c) New File Name to be renamed

All are fine except the c) New File Name to be renamed

$Rename = input

$newName = '$Rename_{0:d6}{1}' -f  $i , $extension  # $rename input cannot be used here # 

I think some thing wrong on the above line, is there any way to get this done?

Write-Host "Renaming Bulk Files" -BackgroundColor Green -ForegroundColor White
$Source = Read-Host "Enter the Source Path Of the Folder, Ex: D:\Test"
$SourceExtension = Read-Host "Enter the Destination File Extension, Ex: *.pdf or *.jpg"
$Rename = Read-Host "Enter the File Name to be renamed"

$i = 0 
Get-ChildItem -Path $Source -Filter $SourceExtension | 
ForEach-Object {
    $extension = $_.Extension
    $newName = '$Rename_{0:d6}{1}' -f  $i , $extension 
    $i++ 
    Rename-Item -Path $_.FullName -NewName $newName 
}

2 Answers 2

1
$newName = '$Rename_{0:d6}{1}' -f  $i , $extension  # $rename input cannot be used here

Why not? This definitely works:

$newName = '{0}_{1:d6}{2}' -f  $Rename, $i, $_.Extension 
0

First, you need to use double quotes rather than single quotes for variable expansion to work:

"$Rename_{0:d6}{1}" -f  $i , $extension 

But there is still a problem. PowerShell thinks that the variable you are referring to is $Rename_. Why? Because underscore is a valid character in variable names. You need to do this:

"$($Rename)_{0:d6}{1}" -f  $i , $extension 

(Or use beatcracker's solution.)

2
  • Another way to specify variable name when it's surrounded by valid characters in a string: "${Rename}_{0:d6}{1}". You can even store variables in file this way: ${C:\Rename.var} = 'MyString'. Apr 14, 2015 at 9:14
  • @beatcracker, I like the round brackets because you can put arbitrary expressions in them: "$(1 + 1)". I didn't know you could store stuff in a file using curly brackets. I think I would use Set-Content instead: 'my string' | Set-Content blah.txt
    – dangph
    Apr 14, 2015 at 13:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .