Home > front end >  Powershell: Extracting parts of file name to create folders and move files into the folder
Powershell: Extracting parts of file name to create folders and move files into the folder

Time:10-21

I am a new starter to powershell and I am trying to achieve the following:

I have a list of files all in the same format: SURNAME_FIRSTNAME_CODE1_CODE2_NAME.pdf/docx etc

I want to create a subfolder named: SURNAME FIRSTNAME CODE1

and then move all of those relavant files into the folder.

I managed to find an article to do it with the first part (i.e SURNAME) but not really sure how to make it work with the others...any help would be greatly appreciated.

Here is what I have so far: (Thanks to a fellow poster for it)

Get-ChildItem -File -Path $directory -Filter "*.*" | 
ForEach-Object {
New-Item -ItemType Directory "$directory$($_.Name.Split("_")[0])" -Force;   
Move-Item -Path $_.FullName -Destination  "$directory$($_.Name.Split("_")[0])\$($_.Name)"      
} 

CodePudding user response:

This is how I'd do it. It uses Group-Object to group files that belong to the same directory, and the format operator to create the directory name. Let me know if you have any questions.

Get-ChildItem $directory -File |
  group { "{0} {1} {2}" -f $_.BaseName.Split("_") } |
  foreach {
    $newDir = Join-Path $directory $_.Name
    New-Item $newDir -ItemType Directory
    $_.Group | Move-Item -Destination $newDir
}
  • Related