Powershell: Creating folders from filenames and moving files to to those folders

  Kiến thức lập trình

C:Library contains 3 folders:

“P1”, “P2”, “P3”

C:LibraryP1 contains the file “T1 – P1”

C:LibraryP2 contains the files “T1 – P2”, “T3 – P2”

C:LibraryP3 contains the files “T1-P3”, “T2 – P3”, “T3 – P3”

I want to end up with 3 new folders in C:Library called “T1”, “T2”, and “T3” such that for k=1, 2, 3,

C:LibraryTk contains all of the files of the form “Tk – Pj” where j=1 or j=2 or j=3.

This is a simplification of some files I’m trying to organise, in reality the contents of each of the folders “Pk” is unknown and the indices run over ranges larger than 1, 2, 3.

I have some basic Python knowledge but have never used Powershell before beyond trying to figure out how to do this task by looking at posts on this site.

I would appreciate any help on how to proceed with this problem.

I have come up with the following process that should be repeated but am not sure how to implement it:

  1. Select the first non-empty folder in C:Library, suppose it is Pi

  2. Select the first file in Pi, suppose it is Tj – Pi

  3. Create a new folder in C:Library with the name “Tj “.

  4. Move all files in C:Library of the form “Tj – Pk” to the folder “Tj“.

  5. Repeat steps 1-4 until all folders in C:Library are empty.

I have tried using the cmdlet

Get-ChildItem

and perhaps I should combine it with -Recurse and -Depth
but I’m not sure this is the best approach.

I have looked at answers to similar questions but I’m not so sure on the syntax.

New contributor

asdf asdf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT