You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中批量重命名含特殊字符的文件?

解决PowerShell重命名含[]特殊字符文件的问题

问题场景

文件夹内有47个MKV文件,文件名均包含[Test],尝试用以下命令批量移除文件名中的[Test]:

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

执行后触发报错:

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

问题根源是[]被PowerShell识别为通配符特殊语法,导致路径解析失败。

解决方案

核心修复:使用-LiteralPath参数

Rename-Item默认会将输入路径当作通配符模式解析,而[]是通配符中用于定义字符匹配集的特殊符号,因此触发格式错误。改用-LiteralPath参数可强制PowerShell按字面量处理路径,忽略所有特殊字符:

Get-ChildItem *.mkv | ForEach-Object { 
    Rename-Item -LiteralPath $_.FullName -NewName $_.Name.Replace("[Test]", "") 
}

简化写法(正则替换)

如果用PowerShell的-Replace正则替换,需要给[]加转义符\,同时搭配-LiteralPath:

Get-ChildItem *.mkv | Rename-Item -LiteralPath { $_.FullName } -NewName { $_.Name -Replace '\[Test\]', '' }

关键说明

  • -LiteralPath是处理含[]、*、?等特殊字符文件名的核心参数,它会完全按照字符串原始内容解析路径,不做任何通配符匹配。
  • 普通字符串的Replace()方法无需转义[],但正则替换的-Replace必须转义这类正则特殊字符。

内容的提问来源于stack exchange,提问作者Mouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:48:17