I have a large amount of files in a single folder, and I want to move all of these files to a new share with folders and sub folders based off the first and 2nd parts of the file names.
An example file name - Wednesday Work - Part 05 - Not Done.docx
An example new folder structure - Wednesday Work -> Part 05 -> *.docx
What’s the best way to be able to compare the Wednesday Work and Part 05 parts of the file name against the folder structure so I can match them up?
I’ve tried working with something like $File.Name.Split(‘-’)[0].TrimEnd()
which seems to work for the first part, but I’m stuck on the rest.
Hello Ryan,
You can apply same logic for the 2nd part - just reference second element of your array after split.
$File.Name.Split(‘-’)[1].TrimEnd()
After spliting file name you receive array with 3 elements:
0 - Wednesday Work
1 - Part 05
2 - Not Done.docx
Hope that helps.
A couple of more options.
Using a couple of variations of your example filename, in case they don’t all have space dash space. They all need to have at least a dash between them and no other dashes in the names of either folder or file.
$examples = 'Teusday Work-Part 04-Done.docx',
'Wednesday Work - Part 05 - Not Done.docx',
'Thursday Work -Part 06 -Not Done1.docx',
'Friday Work- Part 07- Not Done2.docx'
First we’ll use regex with named capture groups for easy reading/understanding
$examples | foreach {
if($_ -match '(?<Folder>.+?)-\s{0,2}(?<Subfolder>.+?)-\s{0,2}(?<file>.+)')
{
Write-Host "Folder: $($Matches.Folder)"
Write-Host "Subfolder: $($Matches.Subfolder)"
Write-Host "File: $($Matches.file)"
}
}
The next we will use -Split which also uses regex. But we’ll take advantage of a very nice powershell feature where we can set each variable at the same time.
$examples | foreach {
$folder,$subfolder,$file = $_ -split '-\s{0,2}'
Write-Host "Folder: $folder"
Write-Host "Subfolder: $Subfolder"
Write-Host "File: $file"
}
No need to use trim on either of these as 0, 1, or 2 spaces would get pulled out in the match. Output for both is
Folder: Teusday Work
Subfolder: Part 04
File: Done.docx
Folder: Wednesday Work
Subfolder: Part 05
File: Not Done.docx
Folder: Thursday Work
Subfolder: Part 06
File: Not Done1.docx
Folder: Friday Work
Subfolder: Part 07
File: Not Done2.docx