powershellspecial-characters

How can I bulk rename files with special characters in PowerShell?


I have 47 files in a folder that have [Test] in the name,

I am trying to use

get-childitem *.mkv | foreach { rename-item $_ $_.Name.Replace("[Test]", "") }

To remove [Test] but I get an error stating: Rename-Item : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid:

[Test] Bulk File Create
At line:1 char:33
+ ...  *.mkv | foreach { rename-item $_ $_.Name.Replace("[Test] ", "") }
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.RenameItemCommand

I am assuming it's seeing the [] as some sort of code and I have to handle them in a special way and I don't know how.


Solution

  • Pipe the output from Get-ChildItem directly to Rename-Item, that way the objects are bound by provider path to the -LiteralPath parameter and any wildcard character is interpreted as literal. See also Using delay-bind script blocks with parameters.

    Get-ChildItem -Filter '*[test]*.mkv' |
        Rename-Item -NewName { $_.Name.Replace('[test]', '') }