Puck
Puck

Reputation: 25

Powershell - create directories form files in a dierectory

I am trying to clean up and group files in a directory by creating subdirectories and then copying the files into the new directories.

Example:

test01.a.jpg
test01.a.txt 
test01.b.bak 
test01.b.txt 
test02.a.txt
test02.a.jpg
test02.a.bak
test03.a.txt
test03.a.bak
test03.b.txt

I wish to create subdirectories like test01, test02, test03 and ideally copy the relevant files over. All groups will have a txt file but more or less of the others.

To create the directories I have got as far as

gci -file *.txt | New-Item -ItemType directory $_.name

which doesn't work as expected.

Upvotes: 0

Views: 120

Answers (2)

FletcherF1
FletcherF1

Reputation: 187

Actually, algorithm is simple (we don't need to previously compare names of files. All we need is just use a $_.BaseName property)

<#Creating folders and moving files using BaseName property #>
gci *.txt | % { new-item -ItemType Directory -Path ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}    
gci -file | % { Move-item $_.Fullname ($_.Directory.ToString() + "\" + $_.BaseName.ToString())} 

Upvotes: 0

Theo
Theo

Reputation: 61028

If your files have names like that, you can simply split the filename on the dot and take only the first part as new folder name.

Then test if a subfolder like that already exists (if not create it) and move the file. Something like this

$sourcePath = 'D:\Test'  # put the real path to the files here

# if you want only the files with extension .txt, use filter '*.*.txt'
(Get-ChildItem -Path $sourcePath -File -Filter '*.*.*') | ForEach-Object {
    # use the first part of the file name for subdirectory name
    $destinationPath = Join-Path -Path $sourcePath -ChildPath $_.Name.Split(".")[0]
    if (!(Test-Path -Path $destinationPath -PathType Container)) {
        # if a subdirectory with that name does not already exist, create it
        $null = New-Item -Path $destinationPath -ItemType Directory
    }
    # now move the file to that (new) destination folder
    $_ | Move-Item -Destination $destinationPath
}

Upvotes: 2

Related Questions