replace names of all directiories and files in PS

前端 未结 3 678
忘了有多久
忘了有多久 2021-01-05 18:56

I want to replace all space characters into \"_\" in names of all subfolders and files. Unfortunately when I type:

Get-ChildItem -recurse -name | ForEach-Obj         


        
相关标签:
3条回答
  • 2021-01-05 19:34

    Adding a filter worked for me:

    Get-ChildItem C:\path-to-directory -Recurse -Filter *foo* | Rename-Item -NewName { $_.name -replace 'foo', 'bar'} -verbose
    
    0 讨论(0)
  • 2021-01-05 19:42

    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 ' ','_' }
    
    0 讨论(0)
  • 2021-01-05 19:53

    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.

    0 讨论(0)
提交回复
热议问题