regex to remove brackets

I have hundreds and hundreds of files in the below formats in a folder called c:\files. I need to user regex to replace the brackets with parenthesis. [ with ( and ] with ). How do I go about doing it?

case - The David VS Jacob [XY-CURRENT.XID123456]_1234568_1.msg
case – PS Lava Employees LLC [ZZ-CURRENT.XID5374648]_47847484_1.MSG
Joh Doe [XX-CURRENT.XID293028]_40000555_1.msg

Hello,

Replacing is fairly easy, in fact you don’t really even need to use RegEx, but here’s an example.

Get-ChildItem -Path C:\Files | ForEach-Object -Process {
    $fileText = Get-Content -Path $PSItem.FullName
    $strOpenBrackets = $fileText -replace '\[', '('
    $strComplete = $strOpenBrackets -replace ']', ')'
    $strComplete |
    Out-String |
    Set-Content -Path $PSItem.FullName -Force
}

Getting the following error:

Get-Content : An object at the specified path C:\Files\case – The David VS Jacob [XY-CURRENT.XID123456]_1234568_1.msg does not exist, or has been filtered by the -Include or
-Exclude parameter.
At C:\Users\username\Desktop\test.ps1:3 char:17

  • $fileText = Get-Content -Path $PSItem.FullName
    
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
    • FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Set-Content : An object at the specified path C:\Files\case – The David VS Jacob [XY-CURRENT.XID123456]_1234568_1.msg does not exist, or has been filtered by the -Include or
-Exclude parameter.
At C:\Users\username\Desktop\test.ps1:8 char:5

  • Set-Content -Path $PSItem.FullName -Force
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (System.String[]:String[]) [Set-Content], Exception
    • FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.SetContentCommand

Do you have any subdirectories in C:\Files by any chance? It could be that it’s trying to read in a directory as a text file. To ensure that it is only the files it attempts to read, you can change the Get-Content command to

Get-ChildItem -Path C:\Files -File

If you still receive the error, then set $ErrorActionPreferenece to ‘Stop’ in your script, and use a Try…Catch block for error trapping. Output the error details in the Catch block to try and get a better idea of what files are causing the issues. Some attribute like $error[0].FullyQualifiedErrorID is probably the easiest for displaying to get an idea whats going on.

I don’t have any subdirectories but I think I figured out a way to do it which worked great (See the one-liner below). Thanks for your help.

Get-ChildItem E:\files -Recurse | Rename-Item -NewName { $_.Name -replace “[”,"(" -replace “]”, “)” }