Extract first 2 white spaces from folder / file name

Roberto Madro R.
Roberto Madro R. used Ask the Experts™
I'm looking for a way to delete the first 2 white spaces from the name of folders / files.

Example: AB 123 John Accounting Department, would become AB123John Accounting Department
Appreciate the thoughts.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
For files, you can use this; it's in test mode and will only display which files it would rename to what. Remove the -WhatIf at the end to run it for real.
Get-ChildItem -Path 'C:\temp\*.txt' -File | Rename-Item -NewName {$_.Name -replace '^(.*?)\s(.*?)\s', '$1$2'} -WhatIf

Open in new window

Rename directories like this; it will first sort them by depth (so that the deepest paths are renamed first); test mode as well:
Get-ChildItem -Path C:\Temp -Directory | Sort-Object @{e={[regex]::Matches($_.FullName, '\\').Count}} -Descending | Rename-Item -NewName {$_.Name -replace '^(.*?)\s(.*?)\s', '$1$2'} -WhatIf

Open in new window

Roberto Madro R.Programmer Analyst


oBdA, thank you, right on the money, much appreciated.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial