sam goto
sam goto

Reputation: 49

How to search for specific files recursively, create folder and move file to it?

How can I search for a specific file extension recursively through out the entire directory structure, for each file/extension found create a folder at the file location using each file's name, and move the file/s to its own folder (that matches the files name)?

Thank you @Alex_P: The following code creates only one folder, and moves ALL the files found into this folder. Is there a way to make it create a folder for each item and then move each item to its corresponding folder. Appreciate your help.

  $_ = (Get-ChildItem -Path "C:\3\ML\300000-310000S\302355\OLn2" -Recurse -File | Where-Object { $_.Extension -eq '.MCX-5' })
    
    ForEach-Object {

  New-Item -Path $_[0].PSParentPath -Name $_[0].BaseName -ItemType Directory

$newpath = Join-Path -Path $_[0].PSParentPath -ChildPath $_[0].BaseName
Move-Item -Path $_.FullName -Destination $newpath -Force

   } 

Upvotes: 0

Views: 353

Answers (1)

Alex_P
Alex_P

Reputation: 2952

Get-ChildItem returns System.IO.FileInfo objects. You can use their property 'Extension' to filter for file extensions.

This example will give you all PDF files:

$files = Get-ChildItem -Path .\Documents\ -Recurse -File | Where-Object { $_.Extension -eq '.pdf' }

In order to move the files you can use some other, useful properties of the object. .PSParentPath gives you the path up to the directory of your object. .BaseName gives you the file name, excluding the extension.

New-Item -Path $files[0].PSParentPath -Name $files[0].BaseName -ItemType Directory

Now, in order to move your item, you need to concatenate your path with your new directory and then you can move the item to your new directory. .Fullname gives you the full path of the object.

$newpath = Join-Path -Path $files[0].PSParentPath -ChildPath $files[0].BaseName
Move-Item -Path $files[0].FullName -Destination $newpath

In my case, I only moved one item but you need to add these to your foreach loop.

Upvotes: 1

Related Questions