Question:
I have a list of files like this:
Test.(file1)[text].txt
Test.(file2)[text].txt
Test.(file3)[text].txt
I need to remove any “()”,”[]” and any “.”, replace them spaces without changing the file extension. I’ve tried the following but it’s not working:
1 2 3 4 5 6 |
dir C:\scratch\*.txt | % { Rename-Item $_ ($_.basename -replace "\(", " "` -replace "\)", " "` -replace "\[", " "` -replace "\]", " "` -replace ".", " ")} |
Ideally the file name should end up in the format “Test file1 text.txt”
Answer:
IMO Rename-Item appears to be broken in terms of its handling of paths with [ ] chars in them. Fortunately, Move-Item works:
1 2 3 |
dir *.txt | mi -dest {($_.Basename -replace '[()[\].]+',' ').Trim() + $_.Extension} |
Where mi
is the alias for Move-Item. Note that a number of cmdlets like Rename-Item and Move-Item can be piped to directly and then their NewName/Destination parameters can take scriptblocks in which you can use the pipeline object. Internally this works for pipeline bound parameters as PowerShell will execute the scriptblock and attempt to coerce the result to the type expected by the parameter.