Remove space bars from file and directory names

Welcome Forums General PowerShell Q&A Remove space bars from file and directory names

This topic contains 2 replies, has 2 voices, and was last updated by

9 months, 2 weeks ago.

  • Author
  • #101834

    Points: 0
    Rank: Member


    Does anyone maybe have an idea how a PS script might be looking like to loop over a directory including sub directories and files and whenever it sees more then one space bar in sequence in a file or directory name it replaces them by a single one?
    The idea is to minimize unnecessary path lengths.


  • #101851

    Points: 6
    Rank: Member

    You can iterate through a directory by using the get-childitem cmdlet. For each iteration you can take the string of the directory name and use the default -split operator to separate the string into an array based on white space. Then take that array and join it back together using the -join operator with white space as the join character. Then rename the directory to the new string using rename-item cmdlet. I would recommend reviewing help on about_split, about_join, get-childitem and rename-item. Here is an example:

    Get-ChildItem -Recurse | % {
        Rename-Item -Path $_.FullName -NewName ((-split $_) -join " ")

    This works because the default for -split is any white space which means multiple spaces act just the same in creating the array. To use the default you put the -split operator in front of the string object.

    • #101857

      Points: 0
      Rank: Member

      This does work as is (except for adding the -Path parameter for Get-ChildItem.
      Many many thanks!!

The topic ‘Remove space bars from file and directory names’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort