in following PowerShell code:
dir "D:\Test\New folder" | Rename-Item -NewName {$_.Name -replace 'PP&C Test (Bank), Ltd.','PP&C Test (Bank) Ltd.'}
what I am trying to do is replace all files within D:\Test\New folder that have PP&C Test (Bank), Ltd. in their filename with PP&C Test (Bank) Ltd. So basically just to remove the comma before Ltd.
When executing the script in PowerShell nothing gets renamed. Any idea why? I believe it is something to do with & and Brackets () as when I'm doing the same for filenames without those chars it works fine.
Thanks!
CodePudding user response:
Or backslash the parens for the regex. I wonder if -replace should give a warning. The parens are used for grouping.
'PP&C Test (Bank), Ltd.' -replace 'PP&C Test \(Bank\), Ltd.',
'PP&C Test (Bank) Ltd.'
PP&C Test (Bank) Ltd.
What escape() returns. I don't see why the spaces are escaped. . means any character.
[regex]::escape('PP&C Test (Bank), Ltd.')
PP&C\ Test\ \(Bank\),\ Ltd\.
It seems to require taking off the period at the end. It's quite odd. I guess there is no period.
dir | rename-item -newname { $_.name -replace '_PP&C Test \(Bank\), Ltd.',
'_PP&C Test (Bank) Ltd.' } -whatif
What if: Performing the operation "Rename File" on target "Item:
C:\users\admin\foo\_PP&C Test (Bank), Ltd Destination:
C:\users\admin\foo\_PP&C Test (Bank), Ltd".
dir | rename-item -newname { $_.name -replace '_PP&C Test \(Bank\), Ltd',
'_PP&C Test (Bank) Ltd' } -whatif
What if: Performing the operation "Rename File" on target "Item:
C:\users\admin\foo\_PP&C Test (Bank), Ltd Destination:
C:\users\admin\foo\_PP&C Test (Bank) Ltd".
To get-childitem there's a period, but not to the name property:
dir '_PP&C Test (Bank), Ltd.'
Directory: C:\Users\admin\foo
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 1/31/2022 12:52 PM 4 _PP&C Test (Bank), Ltd.
dir | % name
_PP&C Test (Bank), Ltd
