Moving Files by Filename to different Directoires

Hi there, I try to clean a folder with thousands of files. The goal is to move the files to diffrent folders sortet by name. All files that start with the lettre A should move to a-folder - and so on.
My script looks like that:

Get-ChildItem -Path 'D:\Test'  |foreach-object {
if($_.name  -like 'a*')
{move-item d:\test\a-folder}
elseif($_.name -like 'b*')
{move-item d:\test\b-folder}
elseif($_.name -like 'c*')
{move-item d:\test\c-folder}
}

The error I get:
Cannot find path ‘D:\test\a-folder’ because it does not exist.
Move-Item:

What it does is, it deletes all three folders: a-folder/b-folder/c-folder
Any suggestions? Thanks so much in advance

Hi zwymar,

check the help for Move-Item and Get-ChildItem.

Move-item is missing path and destination.

also you have the subfolders inside d:\test. if you do get-childitem the directory will be picked up as well. $_.name will most likely cause error when you try to move.

try something like

#add -file to specify you only want the files and not the directories inside
Get-ChildItem -Path 'C:\Users\potato\Documents\test' -File |
ForEach-object {
    if($_.name  -like 'a*') {
        # include path and desitination
        Move-Item -path $_.FullName -destination C:\Users\potato\Documents\test\a-folder
    }
    elseif($_.name -like 'b*') {
        Move-Item -path $_.FullName -destination C:\Users\potato\Documents\test\b-folder
    }
    elseif($_.name -like 'c*') {
        Move-Item -path $_.FullName -destination C:\Users\potato\Documents\test\c-folder
    }
}

test it out with a few files

Hopefully the pros will jump in to give more guidance if I’ve missed something.

Hi mawazo,
perfect, it works fine.
Enjoy your sunday!
Cheers Martin

I think the main problem with the example in your question, and also the solution, by @mawazo, is the the repetitive code. I would do something like this:

$destinationRoot = 'E:\Temp\Test\'

Get-ChildItem E:\Temp\Test\ -File | 
    ForEach-Object {
        $inital = $_.BaseName.Substring(0,1)
        $destinationPath = Join-Path -Path $destinationRoot -ChildPath "$inital-folder"
        if (-not(Test-Path $destinationPath)) {
            New-Item -Path $destinationPath -ItemType Directory
        }
        Move-Item -Path $_ -Destination $destinationPath
    }
2 Likes

Amazing! @matt-bloomfield, thanks for sharing :slight_smile: