Replacing all # in filenames throughout subfolders in Windows

匆匆过客 提交于 2019-12-24 04:34:04

问题


Migrating about 200,000 files to OneDrive for business, and discovered that there are a few characters they don't like - the biggest offender is #. I have about 3,000 files with a hash, and I'd like to replace them all with just No.. For example, old: File#3.txt new: File No.3.txt

I tried using a PowerShell script, but it doesn't like # either:

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

I'm not having much luck figuring out the syntax for reserved characters - I tried \#, #\, '*#*', no luck.

Can anyone shed light on this or provide a quick method to recursively replace all of these hash tags?

Thanks.


回答1:


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 uses the Backtick (`) as an escape character, and double quotes to evaluate content:

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

or

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

Both will work.

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".

This would also work,

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".

Because the PowerShell parser is smart enough to figure out your intent.



来源:https://stackoverflow.com/questions/26647934/replacing-all-in-filenames-throughout-subfolders-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!