Move files to folders based on 2 parts of file name

Welcome Forums General PowerShell Q&A Move files to folders based on 2 parts of file name

Viewing 2 reply threads
  • Author
    • #267398
      Topics: 1
      Replies: 0
      Points: 34
      Rank: Member

      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.

    • #267401
      Topics: 1
      Replies: 55
      Points: 523
      Helping Hand
      Rank: Major Contributor

      Hello Ryan,

      You can apply same logic for the 2nd part – just reference second element of your array after split.


      After spliting file name you receive array with 3 elements:

      0 – Wednesday Work

      1 – Part 05

      2 – Not Done.docx

      Hope that helps.

    • #267515
      Topics: 9
      Replies: 676
      Points: 2,674
      Helping Hand
      Rank: Community Hero

      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.

      First we’ll use regex with named capture groups for easy reading/understanding

      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.

      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

Viewing 2 reply threads
  • You must be logged in to reply to this topic.