Remove space bars from file and directory names

This topic contains 2 replies, has 2 voices, and was last updated by  nixbmu 2 weeks, 3 days ago.

  • Author
    Posts
  • #101834

    nixbmu
    Participant

    Hi

    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.

    Thanks

  • #101851

    Mike R.
    Participant

    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

      nixbmu
      Participant

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

You must be logged in to reply to this topic.