user982201
user982201

Reputation: 71

Powershell - copy files to different destination folders based on file names

Dear Powershell Gurus,

I have a few thousands of files in a folder called C:\Downloads\Signs. The files are named with their dimensions such as 13X20 abcdjd.psf, 8X20 jdscnjfc.psf, 14X24 dje.psf etc. What I want to do is to move these files to destination folders created within the C:\Downloads\Signs and the folder names are the dimensions of the file names. Example the folder names will be 13X20, 8X20, 14X24 etc and it depends upon as many unique file names with their dimensions. So, instead of moving them manually looking at how many files are there in the C:\Downloads\Signs folder and then moving them individually, how can we do it in Powershell?

Thanks, Sanders.

Upvotes: 2

Views: 5184

Answers (1)

Shay Levy
Shay Levy

Reputation: 126942

This script will pick up all psf from the root of the C:\Downloads\Signs folder and will move the files to the destination folders (folders will create if they do not exist):

Get-ChildItem C:\Downloads\Signs -Filter *.psf | Where-Object {!$_.PSIsContainer} | Foreach-Object{

    $dest = Join-Path $_.DirectoryName $_.BaseName.Split()[0]

    if(!(Test-Path -Path $dest -PathType Container))
    {
        $null = md $dest
    }

    $_ | Move-Item -Destination $dest -Force
}

Upvotes: 3

Related Questions