Search code examples
regexpowershellfile-renamesubstring

Rename files using substring extraction


I am using a script to rename files with extension .xml. I need to remove the first 6 characters and truncate the file name to only 11 characters. So far I have script:

Get-ChildItem -Filter "*.xml" | Rename-Item -newname { $_.name.substring(6)} 

How am I able to also have this script remove any characters in the string that are in place 11 or after?

For example a file with name: export12345678910112.xml will result in 12345678910.xml.

The length of the file name is always required to be only 11 characters excluding the extension.


Solution

  • Using the -replace operator with a regular expression is probably the best choice:

    Get-ChildItem -Filter "*.xml" |
      Rename-Item -newname { $_.name -replace '^.{6}(.{11}).*(\.xml)$', '$1$2' } -WhatIf
    

    -WhatIf previews the renaming operation; remove it to perform actual renaming.

    To demonstrate the solution with your sample filename:

    > 'export12345678910112.xml' -replace '^.{6}(.{11}).*(\.xml)$', '$1$2'
    12345678910.xml