在Windows系统的子文件夹中替换文件名中的所有#号

3
迁移约200,000个文件到OneDrive for business时,发现有一些字符不被支持,最大的问题是#。我有大约3,000个带有哈希值的文件,想把它们全部替换成只有No.。例如,原来的文件名:File#3.txt,新的文件名:File No.3.txt
我尝试使用PowerShell脚本,但它也不支持#
Get-ChildItem -Filter "*#*" -Recurse |
  Rename-Item -NewName { $_.name -replace '#',' No. ' }

我在尝试编写保留字符的语法时遇到了一些困难 - 我尝试了\#, #\, '*#*',但都没有成功。

有人能够解决这个问题或者提供一个快速的方法来递归替换所有这些哈希标签吗?

谢谢。


如果您在标签或标题中指定您正在使用的环境,您可能会获得更多答案。 - 4rlekin
1个回答

5
Mode                LastWriteTime     Length Name       
----                -------------     ------ ----      
-a---        30.10.2014     14:58          0 file#1.txt
-a---        30.10.2014     14:58          0 file#2.txt

PowerShell使用反引号(`)作为转义字符,并使用双引号来评估内容:

Get-ChildItem -Filter "*`#*" -Recurse |
Rename-Item -NewName {$_.name -replace '#','No.' } -Verbose

或者

Get-ChildItem -Filter "*$([char]35)*" -Recurse | 
Rename-Item -NewName {$_.name -replace "$([char]35)","No." } -Verbose

两种方法都可以。

Get-ChildItem -Filter "*`#*" -Recurse | 
           Rename-Item -NewName {$_.name -replace "`#","No." } -Verbose

VERBOSE: Performing the operation "Rename File" on target 
"Item: D:\tmp\file#1.txt Destination: D:\tmp\fileNo.1.txt".
VERBOSE: Performing the operation "Rename File" on target 
"Item: D:\tmp\file#2.txt Destination: D:\tmp\fileNo.2.txt".

这也可以工作,
Get-ChildItem -Filter '*#*' -Recurse |
Rename-Item -NewName {$_.name -replace '#', 'No.'} -Verbose

VERBOSE: Performing the operation "Rename File" on target 
"Item: D:\tmp\file#1.txt Destination: D:\tmp\fileNo.1.txt".
VERBOSE: Performing the operation "Rename File" on target
"Item: D:\tmp\file#2.txt Destination: D:\tmp\fileNo.2.txt".

由于PowerShell解析器足够智能,可以理解您的意图。

这里有一篇由Jeffrey Snover撰写的精彩文章,如果你想深入了解字符串中的变量扩展。Http://blogs.msdn.com/b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx - evilSnobu
完美运行...太棒了。一个字符的差别真是大啊。谢谢你。 - Mark Sinford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接