2014-10-30 133 views
2

将大约200,000个文件迁移到OneDrive for business,并发现有几个字符是他们不喜欢的 - 最大的违规者是#。我有大约3000个散列文件,我想用No.来代替它们。例如,旧:File#3.txt新:File No.3.txt替换Windows中所有子文件夹中的所有文件名#

我尝试使用PowerShell脚本,但它不喜欢#之一:

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

我没有多少运气搞清楚的语法保留字符 - 我试过\#,#\,'*#*',没有运气。

任何人都可以阐明这一点或提供一个快速方法来递归替换所有这些哈希标记?

谢谢。

+0

如果您在标签或标题中指定工作环境,可能会得到更多答案 – 4rlekin 2014-10-30 08:24:55

回答

4
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的解析器是足够聪明,找出你的意图。

+0

如果您想更深入地了解字符串中的变量扩展,Jeffrey Snover发布了一篇非常棒的文章。 Http://blogs.msdn.com/b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx – evilSnobu 2014-10-30 20:52:02

+0

完美的作品......辉煌。一个角色可以做出什么改变。谢谢 – 2014-10-30 21:26:09

相关问题