Looking for a way to batch rename files but deleting a string on the end of the file name RRS feed

  • Question

  • Hello!  My problem has to do with renaming several hundred files that I restored from backup that has a string appended, in the form of "original name (date1 time1).jpg".  I want to strip off the " (date1 timei)" part from the original name.  Note that there is a space character between the original name string and the date string, and another space between that and the time string.  Both date and time strings are enclosed together by one set of parentheses.

    I was looking at the cmdlet dir | rename-item -newname {$._name -replace "oldstring","newstring"}, but it does not quite fit the bill at second glance, because it does not seem that the -replace parameter can replace a non-null string with a null character, which is what I need to do to truncate the file names back to their original forms.

    Then I spied one of your blogs that suggested Get-ChildItem -Filter “*current*” -Recurse | Rename-Item -NewName {$ -replace ‘current’,’old’ }.  I realized that "*current*" is being used as the demo string, and I was about to get happy, until I noticed that the rename-item cmdlet was doing the heavy lifting again.  Am I trying to be use rename-item wrong, or is there a subtly that I'm missing?  Or should I be looking at using another cmdlet altogether to get this truncation result.  I am not trying to remove the extension, just the added end of the file name that will follow a predictable pattern.  The original file names are not that predictable.

    Friday, July 12, 2019 1:18 AM


All replies

  • $filename -replace 'some value'

    This will remove the target string form the original.


     'some file <plus other stuff>.txt' -replace ' <plus other stuff>'


    Friday, July 12, 2019 1:38 AM
  • I'm curious why you are showing the use of single quotes instead of double quotes around the string part I need to lop off.  And is $filename a parameter that replaces the $ parameter, or are you saying that would be the actuale file name?  I ran the cmdlet as I thought I understood what you were saying, but without a second string for the -replace switch, I get a bunch of  "source and destination path must be different." errors.
    Friday, July 12, 2019 4:21 AM
  • It is an example to show you how the operator works.

    The Rename command takes a name.

    "replace" is not a switch it is an operator.  YOu need to learn basic PowerShell and all of the will become clear.

    help about_operators

    help about_Quoting_Rules

    Microsoft Virtual   Academy - Getting Started with Microsoft PowerShell


    Friday, July 12, 2019 4:45 AM