2014-10-30 93 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

相關問題