Author Posts

June 5, 2018 at 5:07 pm

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

June 5, 2018 at 6:45 pm

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.

June 5, 2018 at 7:17 pm

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