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?
Select multiple files in a folder. To do so, press and hold down the CTRL key while you are clicking files. After you select the files, press F2. Type the new name, and then press ENTER.
What to Know. Open File Explorer, go to a file folder, select View > Details, select all files, select Home > Rename, enter a file name, and press Enter. In Windows PowerShell, go to a file folder, enter dir | rename-item -NewName {$_.name -replace “My”,”Our”} and press Enter.
You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.
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 ' ','_' }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With