OK first a thanks to nex84 for answering my last question and all those that gave input as well at this link https://superuser.com/a/1051727/569550...

I now have a new question but it ties with the same code as the one in the link.

I have created a script that will remove text from a file name and replace it with new text or a blank.

This was stated in the last question following the link I gave. I have added a user input so the user can input what the text is to be removed and what they want to add.

I get the removal part correct but I am having trouble with the addition of new text to the file name. Any suggestions...

The code below works for the removed but when the rename comes in the script adds "$Rename" to the file name instead of what the user inputs.

Example: If the user removed "-Layout1" but add "-Model" to the file name we get:

BLABLA-Layout1.pdf ==>  BLABLA$Replace.pdf


CD C:\TempPDF 
$Filter = Read-Host -Prompt 'Input Text To Be Removed' 
$Rename = Read-Host -Prompt 'Input Text To Be Added' 
Write-Host "You input server '$Filter' and '$Rename'" 
Get-ChildItem -Filter "*$Filter*" -Recurse | Rename-Item -NewName {$_.name -replace "$Filter",'$Rename' }

Single quotes in Powershell delimits only string values. In this case use double-quotes when passing variable $Rename to the file name.

Get-ChildItem -Filter "*$Filter*" -Recurse | Rename-Item -NewName {$_.name -replace "$Filter","$Rename" }
  • Perfect. Thanks for the quick answer. This works perfectly now. All I need to do now is wrap it in an exe and I can distribute it to my coworkers. You guys are awesome! Thanks again. – Christopher Mar 15 '16 at 17:17
  • This code lets me get away from downloading all the Renaming Utilities out there. Thanks again. – Christopher Mar 15 '16 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.