user6391187
user6391187

Reputation: 87

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.

Upvotes: 1

Views: 531

Answers (1)

mklement0
mklement0

Reputation: 437042

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

Upvotes: 1

Related Questions