Moving files to subfolders

It’s not uncommon for me to have to tidy up directories full of files by moving them to their own subfolders, named for each file. It’s become common enough that I wrote a little Powershell function to do it repeatedly.

After saving the below script as a .psm1 file you’ll be able to open PS and import the file. I tend to save it to “C:\Scripts\MoveToSubfolders.psm1” – then I can open PS and run “Import-Module C:\Scripts\MoveToSubfolders.psm1”.

Once it’s been imported I can then use the function on whatever folder of files I need to tidy by simply running “MoveToSubfolders” and following the function with the folder I need to sort. It works well for making movies tidier.1`

function MoveToSubfolders([string]$Folder = ".\" ){
# Convert relative folder paths to full paths
$FullPath = Resolve-Path $Folder

# Generate list of all files in the specified directory.
$Files = Get-ChildItem -Path ((Get-Item -Path $FullPath -Verbose).FullName)

# For each object in the directory, do the following:
$Files | ForEach-Object {
    # Generate the variables 
    $FileName = $_.FullName
    $FileFolderName = $_.BaseName
    $DestinationFolder = "$FullPath\$FileFolderName"
    $MoveDestination = "$DestinationFolder\$($_.Name)"

    # Check if the destination directory exists
    if(!(Test-Path $DestinationFolder))
    {
        # Create the directory using FileName (minus file extension) if it does not exist
        New-Item -Path $DestinationFolder -ItemType Directory
    }
    # Move the file to the new directory
    Move-Item -ErrorAction SilentlyContinue $FileName $MoveDestination
}
}
# Actually allow this module to have functions used outside via import
Export-ModuleMember -Function *
Export-ModuleMember -Variable *


Permanent link to this article: https://www.berserkir.net/wordpress/moving-files-to-subfolders/