Replace the names of all directiories and files in PS

I want to replace all white space characters with "_" in the names of all subfolders and files. Unfortunately, when I type:

Get-ChildItem -recurse -name | ForEach-Object { Rename-Item $_ $_.replace(" ","_") }

Error message:

Rename item: the source and destination path must be different. By 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 should I improve this short code?

+5
source share
2 answers

, , . Rename-Item. Move-Item:

Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }

, $_.replace(...) , . .

+5

Name, , . :

Get-ChildItem -Recurse | `
   Where-Object {$_.Name -match ' '} | `
     Rename-Item -NewName { $_.Name -replace ' ','_' }
+6

All Articles