Wednesday, August 20, 2025

organize your files based on creation time

 # PowerShell script to organize files into date-based folders

# Creates folders in format: YYYY-MM-DD


# Set the source directory (current directory by default)

$sourceDirectory = Get-Location


# Get all files in the source directory

$files = Get-ChildItem -Path $sourceDirectory -File


Write-Host "Starting file organization..." -ForegroundColor Green

Write-Host "Source directory: $sourceDirectory" -ForegroundColor Yellow


foreach ($file in $files) {

    try {

        # Get the file's creation date and format it as YYYY-MM-DD

        #$fileDate = $file.CreationTime

        $fileDate = $file.LastWriteTime

        $folderName = $fileDate.ToString("yyyy-MM-dd")

        

        # Create the target folder path

        $targetFolder = Join-Path -Path $sourceDirectory -ChildPath $folderName

        

        # Create the folder if it doesn't exist

        if (-not (Test-Path -Path $targetFolder)) {

            New-Item -Path $targetFolder -ItemType Directory -Force | Out-Null

            Write-Host "Created folder: $folderName" -ForegroundColor Cyan

        }

        

        # Move the file to the target folder

        $targetPath = Join-Path -Path $targetFolder -ChildPath $file.Name

        

        # Check if file already exists in target location

        if (Test-Path -Path $targetPath) {

            Write-Host "File already exists in target: $($file.Name) -> $folderName" -ForegroundColor Yellow

        } else {

            Move-Item -Path $file.FullName -Destination $targetPath

            Write-Host "Moved: $($file.Name) -> $folderName" -ForegroundColor Green

        }

        

    } catch {

        Write-Host "Error processing file $($file.Name): $($_.Exception.Message)" -ForegroundColor Red

    }

}


Write-Host "File organization complete!" -ForegroundColor Green


# Display summary of created folders

$createdFolders = Get-ChildItem -Path $sourceDirectory -Directory | Sort-Object Name

Write-Host "`nCreated folders:" -ForegroundColor Yellow

foreach ($folder in $createdFolders) {

    $fileCount = (Get-ChildItem -Path $folder.FullName -File).Count

    Write-Host "  $($folder.Name) ($fileCount files)" -ForegroundColor White

}


No comments:

Post a Comment