Windows – Remove bracket characters in filenames using Powershell

powershellwindows server 2012

I have a large document library stored on a Sharepoint server which has been migrated over from an old Access database, versioning of these documents was controlled by the user and appended at the end of the file name when changes were made.

e.g.

  1. Doc1-test(1.0).doc
  2. Doc1-test(1.1).doc
  3. Doc2-example(2.1).doc
  4. Doc2-example(2.2).doc

We are now using Sharepoint to control versioning and need to delete the version that is in the file name.

I have had moderate success with the following script;

gi * | % { rni $_ ($_.Name -replace '(1.0)', '') }

but I cannot get it to delete the brackets from the file name. So in my testing directory the files changed to the following

Doc1-doc(1.0).doc —– Doc1-doc().doc

Numbers range from 1.0 to around 4.5, and there are over 1200 documents, so I don't mind having to use an individual script for each version number.

Best Answer

The problem you're running into is that PowerShell's -replace uses Regular Expressions for searching.

This means that the brackets (()) in your search query are being interpreted as a RegEx capture group.

In this case, you want to reference them as literal characters, so you need to escape the brackets. In RegEx, this is done with a backslash (\).

So -replace '\(1.0\)','' should do it.

Since you are using RegEx, you can take advantage of it and do them all at once by specifying a "number" character class or "set" of characters instead of an actual version numbers, as your search pattern

So something like:

gi * | % { rni $_ ($_.Name -replace '\(1.[0-9]\)', '') }

Will remove (1.<any number from 0 to 9>) from the file names.

If you want to remove the brackets and anything in between them you can use the "any character (.) any amount of times (*)" RegEx pattern:

ie: -replace '\(.*\)',''

Note: RegEx can surprise you (think outer and inner brackets in a single file name, in this scenario), so make backups of your files and run tests first. :)

Related Question