General

Powershell – Script – New folder for each file using same name

Creates a folder for each file in specified directory with the same name as the file.

Scenario: A folder contains many files belonging to different projects which the user wants to organise by grouping into separate folders.

[code lang="powershell"]
# Creates a folder for each file in specified directory with the same name as the file.
function CreateSameNameFolders($DirLocation)
{
    # Create list of files in specified folder
    $Files = Get-ChildItem -Path $DirLocation -File

    # Exit function if no files exist in specified folder 
    if($Files.Length -eq 0)
    {
        Write-Output "No files found in specified folder. No folders created"
        return
    }

    # Uncomment the line below to see the list of filenames in console
    # Write-Output $Files

    # Create a directory for each file in the specified folder 
    # To aid process checking, a count of folders created is used
    $FoldCounter = 0    
    ForEach($CurFile in $Files)
    { 
        $NewDirPath = -join($DirLocation,"\",$CurFile.BaseName)
        if(Test-Path $NewDirPath)
        {
            # Keep count of times folder already existed
            $FoldCounter++
        }
        else 
        {
            new-item -Path $CurFile.Directory -Name $CurFile.BaseName -ItemType Directory
        }
    }
    # Output the new folder count to aid checks
    Write-Output "There was $FoldCounter folders that already existed and thus were not newly created"

    # Put each file in '$Files' variable into directory with that name
    ForEach($CurFile in $Files)
    {
        move-item -Path $CurFile.FullName -Destination (-join($CurFile.DirectoryName,"\",$CurFile.BaseName))
    }
}

# Call the function using the path to the files to be inserted into new folders...
$CurLocation = "C:\_Path\To\Files"
CreateSameNameFolders($CurLocation)
[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *