Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace names of all directiories and files in PS

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?

like image 374
matandked Avatar asked Dec 15 '11 10:12

matandked


People also ask

How do I rename all folders at once?

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.

How do I bulk rename files in PowerShell?

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.

Is there a way to rename multiple files at once with different names?

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.


2 Answers

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 ' ','_' }
like image 147
Shay Levy Avatar answered Oct 02 '22 16:10

Shay Levy


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.

like image 30
Stefan Avatar answered Oct 02 '22 16:10

Stefan