Using Regex to replace just square brackets

I have been tasked to rename 1000s of folders, the folders currently look like

D:\MainFolder\Subfolder\clients\Client XYZ [XYZ0001]

What we are after is to replace the square brackets with normal brackets, the problem is only the folders where the customer code is at the end of the name. for example the above folder name should now look like this:

D:\MainFolder\Subfolder\clients\Client XYZ (XYZ0001)

But where we have folder like these we need to ignore them, so I solved that one myself with ‘$’
D:\MainFolder\Subfolder\clients[Lost Clients]
D:\MainFolder\Subfolder\clients[New Clients]
D:\MainFolder\Subfolder\clients\Cient ABC [ABC345] Wound up 2021

Here is what I have that works so far:

$Folders = Get-ChildItem -LiteralPath D:\MainFolder\Subfolder\clients\ -Directory | Where-Object {$_.Name -match “[([^]]+)]$”}

foreach ($fld in $Folders){

       $NewName = $fld.Name -replace '\[', '('

}

This works well in finding folders with square brackets customer code at the end of the name and replacing the first square bracket, I could use a bit of help with this as I can’t seem to replace both sides in a single command.
Doesn’t matter how I go about it, PowerShell complains.

I could run it through twice, as in do the first bracket replacement, and then run it again to do the second.
However I would like firstly to learn and secondly to create a more elegant solution.

My PSVersion 5.1.14393.5066

Any help and guidance would be greatly appreciated

Chadley

Hi, welcome to the forum :wave:

You can chain -replace operators:

$NewName = $fld.Name -replace '\[', '(' -replace '\]',')'
1 Like

You could use a capture group to grab the content between the brackets while replacing them.

$fld.name -replace ‘\[(.+?)\]’,’($1)’
1 Like

Thanks Matt, I actually knew this, just did think of it… So thank you that works.

Thank you Krzydoug, I like it. Not sure I understand how it works tho… Will do some research :slight_smile: