Change folder name with the name between ( ) with powershell

I have a folder structure and in all the folders there is a part between ( ).
Like "folder example(12345)"
Now I must rename all the folders with the name that is between ( ).
So the result is folder "12345"

I have an beginning and then I am stuck.

# Root path
$RootPath = "E:\Test\"
# Rename folders
Get-ChildItem -Path $RootPath -Filter '*()*' -Directory -Depth 0 | Rename-Item -NewName

2 Answers

Based on the answer of Saaru Lindestøkke I can confirm that the script should be working fine.

Here is the code that worked for me:

# Root path
$RootPath = "C:\Temp\"
# Rename folders
Get-ChildItem -Path $RootPath -Filter '*(*)*' | Rename-Item -NewName { $_.Name -replace '.*\((.+?)\).*', '$1' }

I took your example, changed

*()*

to

*(*)*

otherwise it doesn't find anything since it looks for Wildcard()Wildcard and I also changed $RootPath to "C:\TEMP" (It works both with and without \ after TEMP) and only ran the part of Get-ChildItem to see the result. It would always find the folder(s) I created.

I removed as well "-Directory -Depth 0" since I didn't know if it was needed but never the less it should be working.

2

This command will rename folder example(12345) to 12345:

# Root path
$RootPath = "E:\Test\"
# Rename folders
Get-ChildItem -Path $RootPath -Filter '*(*)*' -Directory -Depth 0 | Rename-Item -NewName { $_.Name -replace '.*\((.+?)\).*', '$1' }

What the rename command does:

Get-ChildItem Get items in the folder -Path $RootPath specified in this variable. -Filter '*(*)*' Only take items that match this search -Directory Only take directories -Depth 0 Only look in the current directory level | Forward the result to the next command Rename-Item Rename the incoming items -NewName Specify what the new name should be { $_.Name Take the name of the item to be renamed -replace replace that name '.*\((.+?)\).*', matching a regular expression '$1' with the first capture group (see below for more explanation) }

The regex can be further explained:

.* Match any character 0 or more times
\( Match a literal left parenthesis
(.+?) Capture a group containing any character occurring more than once, but as few times as possible.
\) Match a literal right parenthesis
.* Match any character 0 or more times

The captured group can be reused by referring to it with $1.

A demonstration:

enter image description here

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like