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
This is because replace
uses regex and parentheses (capturing group) should be escaped. The easiest way to escape all text is to use [regex]::Escape method:
gi * | % { rni $_ ($_.Name -replace [regex]::Escape('(1.0)'), '') }
Note, that just removing everything in parentheses will create conflicts for files such as Doc1-test(1.1).doc
and Doc1-test(1.0).doc
- they both will be mapped to Doc1-test.doc
.
Here is my version with regex that will match only dot-separated digits inside parentheses at the end of the filename without extension. I don't handle filename conflicts in this code, because I don't know your desired result.
# Get all objects in current directory that match wildcard: *(*.*).doc
Get-ChildItem -Path '.\' -Filter '*(*.*).doc' |
# Skip folders, because XXX(1.1).doc is a valid folder name
Where-Object {!$_.PSIsContainer} |
# For each file
ForEach-Object {
# New file name =
# File Directory + (File name w\o extension with regex pattern (\(\d+\.\d+\))$ replaced with empty string) + File extension
# Note, that it will create confilcts for files such as Doc1-test(1.1).doc and Doc1-test(1.0).doc,
# both of them will end with name Doc1-test.doc
$NewFileName = Join-Path -Path $_.DirectoryName -ChildPath (($_.BaseName -replace '(\(\d+\.\d+\))$', [string]::Empty) + $_.Extension)
# Basic logging
Write-Host "Renaming: $($_.FullName) -> $NewFileName"
# Rename file.
Rename-Item -Path $_.FullName -NewName $NewFileName
}
Explanation of the regex (\(\d+\.\d+\))$
1st Capturing group (\(\d+\.\d+\))
\( matches the character ( literally
\d+ match a digit [0-9]
Quantifier: + Between one and unlimited times,
as many times as possible, giving back as needed [greedy]
\. matches the character . literally
\d+ match a digit [0-9]
Quantifier: + Between one and unlimited times,
as many times as possible, giving back as needed [greedy]
\) matches the character ) literally
$ assert position at end of the string