问题
I want to replace all space characters into "_" in names of all subfolders and files. Unfortunately when I type:
Get-ChildItem -recurse -name | ForEach-Object { Rename-Item $_ $_.replace(" ","_") }
Error message:
Rename-Item : Source and destination path must be different. At line:1 char:60 + Get-ChildItem -recurse -name | ForEach-Object { Rename-Item <<<< $_ $.replace(" ","") } + CategoryInfo : WriteError: (PATH_HERE) [Rename-Item], IOException + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
How I should improve this short code?
回答1:
Don't use the Name switch, it outputs only the names of the objects, not their full path. Try this:
Get-ChildItem -Recurse | `
Where-Object {$_.Name -match ' '} | `
Rename-Item -NewName { $_.Name -replace ' ','_' }
回答2:
The issue here is that if there is no space in the file name the name does not change. This is not supported by Rename-Item
. You should use Move-Item
instead:
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
Additionally, in your answer you missed the underscore in $_.replace(...)
plus you where replacing spaces with an empty string. Included this in my answer.
来源:https://stackoverflow.com/questions/8518518/replace-names-of-all-directiories-and-files-in-ps