Advanced File and Folder Management Toolkit

<#
.SYNOPSIS
Advanced File and Folder Management Toolkit

.DESCRIPTION
This script provides a comprehensive set of tools for managing, analyzing, and manipulating files and folders.
It includes advanced features like recursive operations, detailed file analysis, and complex search capabilities.

.NOTES
File Name      : AdvancedFileAndFolderToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, appropriate permissions
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\AdvancedFileAndFolderToolkit.ps1
#>

# Global variables
$global:sourcePath = ""
$global:destinationPath = ""
$global:reportPath = "$env:USERPROFILE\Desktop\Advanced_File_Folder_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

function Show-Menu {
    Clear-Host
    Write-Host "=== Advanced File and Folder Management Toolkit ===" -ForegroundColor Cyan
    Write-Host "Current Source Path: $global:sourcePath"
    Write-Host "Current Destination Path: $global:destinationPath"
    Write-Host "1.  Set Source Path"
    Write-Host "2.  Set Destination Path"
    Write-Host "3.  Copy Files/Folders"
    Write-Host "4.  Move Files/Folders"
    Write-Host "5.  Delete Files/Folders"
    Write-Host "6.  Rename Files/Folders"
    Write-Host "7.  Analyze Folder Structure"
    Write-Host "8.  Advanced File Search"
    Write-Host "9.  Compare Folders"
    Write-Host "10. Generate File Hashes"
    Write-Host "11. Analyze File Types"
    Write-Host "12. Find Duplicate Files"
    Write-Host "13. Compress Folder"
    Write-Host "14. Extract Archive"
    Write-Host "15. Set File Attributes"
    Write-Host "16. Generate Comprehensive HTML Report"
    Write-Host "17. Exit"
}

function Set-SourcePath {
    $path = Read-Host "Enter the source path"
    if (Test-Path -Path $path) {
        $global:sourcePath = $path
        Write-Host "Source path set to: $global:sourcePath" -ForegroundColor Green
    } else {
        Write-Host "Invalid path. Please try again." -ForegroundColor Red
    }
}

function Set-DestinationPath {
    $path = Read-Host "Enter the destination path"
    if (Test-Path -Path $path) {
        $global:destinationPath = $path
        Write-Host "Destination path set to: $global:destinationPath" -ForegroundColor Green
    } else {
        Write-Host "Invalid path. Please try again." -ForegroundColor Red
    }
}

function Copy-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath) -or [string]::IsNullOrEmpty($global:destinationPath)) {
        Write-Host "Please set both source and destination paths first." -ForegroundColor Red
        return
    }

    Write-Host "`nCopying Files and Folders..." -ForegroundColor Yellow
    try {
        $items = Get-ChildItem -Path $global:sourcePath -Recurse
        $totalItems = $items.Count
        $copiedItems = 0

        foreach ($item in $items) {
            $targetPath = $item.FullName.Replace($global:sourcePath, $global:destinationPath)
            Copy-Item -Path $item.FullName -Destination $targetPath -Force
            $copiedItems++
            Write-Progress -Activity "Copying Files and Folders" -Status "$copiedItems of $totalItems copied" -PercentComplete (($copiedItems / $totalItems) * 100)
        }

        Write-Progress -Activity "Copying Files and Folders" -Completed
        Write-Host "Copy operation completed successfully." -ForegroundColor Green
    }
    catch {
        Write-Host "Error during copy operation: $_" -ForegroundColor Red
    }
}

function Move-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath) -or [string]::IsNullOrEmpty($global:destinationPath)) {
        Write-Host "Please set both source and destination paths first." -ForegroundColor Red
        return
    }

    Write-Host "`nMoving Files and Folders..." -ForegroundColor Yellow
    try {
        $items = Get-ChildItem -Path $global:sourcePath -Recurse
        $totalItems = $items.Count
        $movedItems = 0

        foreach ($item in $items) {
            $targetPath = $item.FullName.Replace($global:sourcePath, $global:destinationPath)
            Move-Item -Path $item.FullName -Destination $targetPath -Force
            $movedItems++
            Write-Progress -Activity "Moving Files and Folders" -Status "$movedItems of $totalItems moved" -PercentComplete (($movedItems / $totalItems) * 100)
        }

        Write-Progress -Activity "Moving Files and Folders" -Completed
        Write-Host "Move operation completed successfully." -ForegroundColor Green
    }
    catch {
        Write-Host "Error during move operation: $_" -ForegroundColor Red
    }
}

function Delete-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $confirmation = Read-Host "Are you sure you want to delete the contents of $global:sourcePath? (Y/N)"
    if ($confirmation -eq "Y") {
        Write-Host "`nDeleting Files and Folders..." -ForegroundColor Yellow
        try {
            $items = Get-ChildItem -Path $global:sourcePath -Recurse
            $totalItems = $items.Count
            $deletedItems = 0

            foreach ($item in $items) {
                Remove-Item -Path $item.FullName -Force -Recurse
                $deletedItems++
                Write-Progress -Activity "Deleting Files and Folders" -Status "$deletedItems of $totalItems deleted" -PercentComplete (($deletedItems / $totalItems) * 100)
            }

            Write-Progress -Activity "Deleting Files and Folders" -Completed
            Write-Host "Delete operation completed successfully." -ForegroundColor Green
        }
        catch {
            Write-Host "Error during delete operation: $_" -ForegroundColor Red
        }
    }
    else {
        Write-Host "Delete operation cancelled." -ForegroundColor Yellow
    }
}

function Rename-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $pattern = Read-Host "Enter the current name pattern (use * for wildcards)"
    $replacement = Read-Host "Enter the new name pattern"
    
    Write-Host "`nRenaming Files and Folders..." -ForegroundColor Yellow
    try {
        $items = Get-ChildItem -Path $global:sourcePath -Recurse -Filter $pattern
        $totalItems = $items.Count
        $renamedItems = 0

        foreach ($item in $items) {
            $newName = $item.Name -replace $pattern, $replacement
            Rename-Item -Path $item.FullName -NewName $newName
            $renamedItems++
            Write-Progress -Activity "Renaming Files and Folders" -Status "$renamedItems of $totalItems renamed" -PercentComplete (($renamedItems / $totalItems) * 100)
        }

        Write-Progress -Activity "Renaming Files and Folders" -Completed
        Write-Host "Rename operation completed successfully." -ForegroundColor Green
    }
    catch {
        Write-Host "Error during rename operation: $_" -ForegroundColor Red
    }
}

function Analyze-FolderStructure {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    Write-Host "`nAnalyzing Folder Structure..." -ForegroundColor Yellow
    try {
        $analysis = Get-ChildItem -Path $global:sourcePath -Recurse | Measure-Object -Property Length -Sum
        $largestFiles = Get-ChildItem -Path $global:sourcePath -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10
        $oldestFiles = Get-ChildItem -Path $global:sourcePath -Recurse -File | Sort-Object CreationTime | Select-Object -First 10
        $newestFiles = Get-ChildItem -Path $global:sourcePath -Recurse -File | Sort-Object CreationTime -Descending | Select-Object -First 10

        $result = [PSCustomObject]@{
            TotalFiles = $analysis.Count
            TotalSize = "{0:N2} MB" -f ($analysis.Sum / 1MB)
            Directories = (Get-ChildItem -Path $global:sourcePath -Directory -Recurse).Count
            AverageFileSize = "{0:N2} KB" -f (($analysis.Sum / $analysis.Count) / 1KB)
            LargestFiles = $largestFiles | Select-Object Name, @{Name="Size(MB)"; Expression={"{0:N2}" -f ($_.Length / 1MB)}}
            OldestFiles = $oldestFiles | Select-Object Name, CreationTime
            NewestFiles = $newestFiles | Select-Object Name, CreationTime
        }
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error during folder analysis: $_" -ForegroundColor Red
        return $null
    }
}

function Advanced-FileSearch {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $searchPattern = Read-Host "Enter the search pattern (e.g., *.txt)"
    $contentSearch = Read-Host "Enter content to search for (optional)"
    $minSize = Read-Host "Enter minimum file size in bytes (optional)"
    $maxSize = Read-Host "Enter maximum file size in bytes (optional)"
    $afterDate = Read-Host "Enter 'after' date (yyyy-MM-dd) (optional)"
    $beforeDate = Read-Host "Enter 'before' date (yyyy-MM-dd) (optional)"

    Write-Host "`nPerforming Advanced File Search..." -ForegroundColor Yellow
    try {
        $searchParams = @{
            Path = $global:sourcePath
            Recurse = $true
            File = $true
        }

        if ($searchPattern) { $searchParams.Filter = $searchPattern }
        if ($minSize) { $searchParams.MinimumSize = [long]$minSize }
        if ($maxSize) { $searchParams.MaximumSize = [long]$maxSize }
        if ($afterDate) { $searchParams.CreationTimeStart = [datetime]::ParseExact($afterDate, "yyyy-MM-dd", $null) }
        if ($beforeDate) { $searchParams.CreationTimeEnd = [datetime]::ParseExact($beforeDate, "yyyy-MM-dd", $null) }

        $results = Get-ChildItem @searchParams

        if ($contentSearch) {
            $results = $results | Where-Object { Get-Content $_.FullName -Raw | Select-String -Pattern $contentSearch -Quiet }
        }

        $results | Format-Table Name, LastWriteTime, Length -AutoSize
        return $results
    }
    catch {
        Write-Host "Error during advanced file search: $_" -ForegroundColor Red
        return $null
    }
}

function Compare-Folders {
    if ([string]::IsNullOrEmpty($global:sourcePath) -or [string]::IsNullOrEmpty($global:destinationPath)) {
        Write-Host "Please set both source and destination paths first." -ForegroundColor Red
        return
    }

    Write-Host "`nComparing Folders..." -ForegroundColor Yellow
    try {
        $comparison = Compare-Object -ReferenceObject (Get-ChildItem -Path $global:sourcePath -Recurse) -DifferenceObject (Get-ChildItem -Path $global:destinationPath -Recurse) -Property Name, Length, LastWriteTime
        if ($comparison) {
            $comparison | Format-Table Name, Length, LastWriteTime, @{Label="Status"; Expression={if ($_.SideIndicator -eq "<=") {"Only in Source"} else {"Only in Destination"}}} -AutoSize
        } else {
            Write-Host "The folders are identical." -ForegroundColor Green
        }
        return $comparison
    }
    catch {
        Write-Host "Error during folder comparison: $_" -ForegroundColor Red
        return $null
    }
}

function Generate-FileHashes {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    Write-Host "`nGenerating File Hashes..." -ForegroundColor Yellow
    try {
        $files = Get-ChildItem -Path $global:sourcePath -Recurse -File
        $hashes = @()
        foreach ($file in $files) {
            $hash = Get-FileHash -Path $file.FullName -Algorithm SHA256
            $hashes += [PSCustomObject]@{
                FileName = $file.Name
                FilePath = $file.FullName
                FileHash = $hash.Hash
            }
        }
        $hashes | Format-Table -AutoSize
        return $hashes
    }
    catch {
        Write-Host "Error generating file hashes: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-FileTypes {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    Write-Host "`nAnalyzing File Types..." -ForegroundColor Yellow
    try {
        $files = Get-ChildItem -Path $global:sourcePath -Recurse -File
        $fileTypes = $files | Group-Object Extension | Sort-Object Count -Descending | Select-Object Name, Count, @{Name="TotalSize(MB)"; Expression={"{0:N2}" -f (($_.Group | Measure-Object Length -Sum).Sum / 1MB)}}
        $fileTypes | Format-Table -AutoSize
        return $fileTypes
    }
    catch {
        Write-Host "Error analyzing file types: $_" -ForegroundColor Red
        return $null
    }
}

function Find-DuplicateFiles {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    Write-Host "`nFinding Duplicate Files..." -ForegroundColor Yellow
    try {
        $files = Get-ChildItem -Path $global:sourcePath -Recurse -File
        $hashes = @{}
        $duplicates = @()

        foreach ($file in $files) {
            $hash = Get-FileHash -Path $file.FullName -Algorithm SHA256
            if ($hashes.ContainsKey($hash.Hash)) {
                $duplicates += [PSCustomObject]@{
                    OriginalFile = $hashes[$hash.Hash]
                    DuplicateFile = $file.FullName
                    FileHash = $hash.Hash
                }
            } else {
                $hashes[$hash.Hash] = $file.FullName
            }
        }

        if ($duplicates.Count -eq 0) {
            Write-Host "No duplicate files found." -ForegroundColor Green
        } else {
            $duplicates | Format-Table -AutoSize
        }
        return $duplicates
    }
    catch {
        Write-Host "Error finding duplicate files: $_" -ForegroundColor Red
        return $null
    }
}

function Compress-Folder {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $archivePath = Read-Host "Enter the path for the compressed file (including filename.zip)"
    
    Write-Host "`nCompressing Folder..." -ForegroundColor Yellow
    try {
        Compress-Archive -Path $global:sourcePath -DestinationPath $archivePath -Force
        Write-Host "Folder compressed successfully to: $archivePath" -ForegroundColor Green
    }
    catch {
        Write-Host "Error compressing folder: $_" -ForegroundColor Red
    }
}

function Extract-Archive {
    $archivePath = Read-Host "Enter the path of the archive to extract"
    $extractPath = Read-Host "Enter the extraction destination path"

    Write-Host "`nExtracting Archive..." -ForegroundColor Yellow
    try {
        Expand-Archive -Path $archivePath -DestinationPath $extractPath -Force
        Write-Host "Archive extracted successfully to: $extractPath" -ForegroundColor Green
    }
    catch {
        Write-Host "Error extracting archive: $_" -ForegroundColor Red
    }
}

function Set-FileAttributes {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $attributes = Read-Host "Enter attributes to set (e.g., ReadOnly, Hidden, Archive)"
    
    Write-Host "`nSetting File Attributes..." -ForegroundColor Yellow
    try {
        $files = Get-ChildItem -Path $global:sourcePath -Recurse -File
        foreach ($file in $files) {
            $file.Attributes = $attributes
        }
        Write-Host "File attributes set successfully." -ForegroundColor Green
    }
    catch {
        Write-Host "Error setting file attributes: $_" -ForegroundColor Red
    }
}

function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating Comprehensive HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced File and Folder Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Advanced File and Folder Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>Source Path: $global:sourcePath</p>
    <p>Destination Path: $global:destinationPath</p>

    <h2>Folder Structure Analysis</h2>
    $($AllResults.FolderAnalysis | ConvertTo-Html -Fragment)

    <h2>File Search Results</h2>
    $($AllResults.FileSearch | ConvertTo-Html -Fragment)

    <h2>Folder Comparison</h2>
    $($AllResults.FolderComparison | ConvertTo-Html -Fragment)

    <h2>File Hashes</h2>
    $($AllResults.FileHashes | ConvertTo-Html -Fragment)

    <h2>File Type Analysis</h2>
    $($AllResults.FileTypes | ConvertTo-Html -Fragment)

    <h2>Duplicate Files</h2>
    $($AllResults.DuplicateFiles | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-17)"

    switch ($choice) {
        "1" { Set-SourcePath }
        "2" { Set-DestinationPath }
        "3" { Copy-FilesAndFolders }
        "4" { Move-FilesAndFolders }
        "5" { Delete-FilesAndFolders }
        "6" { Rename-FilesAndFolders }
        "7" { $allResults.FolderAnalysis = Analyze-FolderStructure }
        "8" { $allResults.FileSearch = Advanced-FileSearch }
        "9" { $allResults.FolderComparison = Compare-Folders }
        "10" { $allResults.FileHashes = Generate-FileHashes }
        "11" { $allResults.FileTypes = Analyze-FileTypes }
        "12" { $allResults.DuplicateFiles = Find-DuplicateFiles }
        "13" { Compress-Folder }
        "14" { Extract-Archive }
        "15" { Set-FileAttributes }
        "16" { Generate-HTMLReport -AllResults $allResults }
        "17" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "17") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "17")

This Advanced File and Folder Management Toolkit includes:

  1. A comprehensive menu-driven interface.
  2. Advanced functions for file and folder operations:
    • Recursive copy, move, and delete operations with progress bars
    • Pattern-based file and folder renaming
    • Detailed folder structure analysis
    • Advanced file search with multiple criteria
    • Folder comparison
    • File hash generation
    • File type analysis
    • Duplicate file detection
    • Folder compression and archive extraction
    • File attribute setting
  3. Comprehensive HTML report generation.

Key features:

  • Flexible path setting for source and destination
  • Advanced file operations with progress tracking
  • Detailed folder analysis including largest and oldest/newest files
  • Complex file search capabilities (pattern, content, size, date)
  • File type distribution analysis
  • Duplicate file detection using hash comparison
  • Built-in compression and extraction tools
  • File attribute manipulation
  • Comprehensive HTML report for all analyses

This tool is particularly useful for:

  • System administrators managing complex file systems
  • IT professionals performing advanced file and folder operations
  • Data analysts needing to understand file distributions and duplicates
  • Anyone requiring detailed file system analysis and management capabilities

To use this script effectively:

  1. Run PowerShell with appropriate permissions to access and modify the file system
  2. Set the source and destination paths before performing operations
  3. Use caution with delete and rename operations, as they can be irreversible
  4. Review the generated HTML report for a comprehensive overview of all analyses

This advanced script provides a powerful set of tools for file and folder management and analysis, suitable for both routine tasks and complex file system operations. It offers detailed insights into file structures, helps identify issues like duplicates, and provides utilities for efficient file management.

File and Folder Manipulation Toolkit

<#
.SYNOPSIS
File and Folder Manipulation Toolkit

.DESCRIPTION
This script provides a set of tools for manipulating and analyzing files and folders,
including operations like copying, moving, deleting, renaming, and analyzing.

.NOTES
File Name      : FileAndFolderToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, appropriate permissions
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\FileAndFolderToolkit.ps1
#>

# Global variables
$global:sourcePath = ""
$global:destinationPath = ""
$global:reportPath = "$env:USERPROFILE\Desktop\File_Folder_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

function Show-Menu {
    Clear-Host
    Write-Host "=== File and Folder Manipulation Toolkit ===" -ForegroundColor Cyan
    Write-Host "Current Source Path: $global:sourcePath"
    Write-Host "Current Destination Path: $global:destinationPath"
    Write-Host "1. Set Source Path"
    Write-Host "2. Set Destination Path"
    Write-Host "3. Copy Files/Folders"
    Write-Host "4. Move Files/Folders"
    Write-Host "5. Delete Files/Folders"
    Write-Host "6. Rename Files/Folders"
    Write-Host "7. Analyze Folder Structure"
    Write-Host "8. Search for Files"
    Write-Host "9. Compare Folders"
    Write-Host "10. Generate File Hash"
    Write-Host "11. Generate HTML Report"
    Write-Host "12. Exit"
}

function Set-SourcePath {
    $path = Read-Host "Enter the source path"
    if (Test-Path -Path $path) {
        $global:sourcePath = $path
        Write-Host "Source path set to: $global:sourcePath" -ForegroundColor Green
    } else {
        Write-Host "Invalid path. Please try again." -ForegroundColor Red
    }
}

function Set-DestinationPath {
    $path = Read-Host "Enter the destination path"
    if (Test-Path -Path $path) {
        $global:destinationPath = $path
        Write-Host "Destination path set to: $global:destinationPath" -ForegroundColor Green
    } else {
        Write-Host "Invalid path. Please try again." -ForegroundColor Red
    }
}

function Copy-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath) -or [string]::IsNullOrEmpty($global:destinationPath)) {
        Write-Host "Please set both source and destination paths first." -ForegroundColor Red
        return
    }

    Write-Host "`nCopying Files and Folders..." -ForegroundColor Yellow
    try {
        Copy-Item -Path $global:sourcePath -Destination $global:destinationPath -Recurse -Force
        Write-Host "Copy operation completed successfully." -ForegroundColor Green
    }
    catch {
        Write-Host "Error during copy operation: $_" -ForegroundColor Red
    }
}

function Move-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath) -or [string]::IsNullOrEmpty($global:destinationPath)) {
        Write-Host "Please set both source and destination paths first." -ForegroundColor Red
        return
    }

    Write-Host "`nMoving Files and Folders..." -ForegroundColor Yellow
    try {
        Move-Item -Path $global:sourcePath -Destination $global:destinationPath -Force
        Write-Host "Move operation completed successfully." -ForegroundColor Green
    }
    catch {
        Write-Host "Error during move operation: $_" -ForegroundColor Red
    }
}

function Delete-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $confirmation = Read-Host "Are you sure you want to delete the contents of $global:sourcePath? (Y/N)"
    if ($confirmation -eq "Y") {
        Write-Host "`nDeleting Files and Folders..." -ForegroundColor Yellow
        try {
            Remove-Item -Path $global:sourcePath -Recurse -Force
            Write-Host "Delete operation completed successfully." -ForegroundColor Green
        }
        catch {
            Write-Host "Error during delete operation: $_" -ForegroundColor Red
        }
    }
    else {
        Write-Host "Delete operation cancelled." -ForegroundColor Yellow
    }
}

function Rename-FilesAndFolders {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $newName = Read-Host "Enter the new name"
    Write-Host "`nRenaming File/Folder..." -ForegroundColor Yellow
    try {
        Rename-Item -Path $global:sourcePath -NewName $newName
        Write-Host "Rename operation completed successfully." -ForegroundColor Green
        $global:sourcePath = Join-Path (Split-Path $global:sourcePath -Parent) $newName
    }
    catch {
        Write-Host "Error during rename operation: $_" -ForegroundColor Red
    }
}

function Analyze-FolderStructure {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    Write-Host "`nAnalyzing Folder Structure..." -ForegroundColor Yellow
    try {
        $analysis = Get-ChildItem -Path $global:sourcePath -Recurse | Measure-Object -Property Length -Sum
        $result = [PSCustomObject]@{
            TotalFiles = $analysis.Count
            TotalSize = "{0:N2} MB" -f ($analysis.Sum / 1MB)
            Directories = (Get-ChildItem -Path $global:sourcePath -Directory -Recurse).Count
        }
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error during folder analysis: $_" -ForegroundColor Red
        return $null
    }
}

function Search-Files {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    $searchPattern = Read-Host "Enter the search pattern (e.g., *.txt)"
    Write-Host "`nSearching for Files..." -ForegroundColor Yellow
    try {
        $results = Get-ChildItem -Path $global:sourcePath -Recurse -Filter $searchPattern
        $results | Format-Table Name, LastWriteTime, Length -AutoSize
        return $results
    }
    catch {
        Write-Host "Error during file search: $_" -ForegroundColor Red
        return $null
    }
}

function Compare-Folders {
    if ([string]::IsNullOrEmpty($global:sourcePath) -or [string]::IsNullOrEmpty($global:destinationPath)) {
        Write-Host "Please set both source and destination paths first." -ForegroundColor Red
        return
    }

    Write-Host "`nComparing Folders..." -ForegroundColor Yellow
    try {
        $comparison = Compare-Object -ReferenceObject (Get-ChildItem -Path $global:sourcePath -Recurse) -DifferenceObject (Get-ChildItem -Path $global:destinationPath -Recurse) -Property Name, Length, LastWriteTime
        if ($comparison) {
            $comparison | Format-Table Name, Length, LastWriteTime, @{Label="Status"; Expression={if ($_.SideIndicator -eq "<=") {"Only in Source"} else {"Only in Destination"}}} -AutoSize
        } else {
            Write-Host "The folders are identical." -ForegroundColor Green
        }
        return $comparison
    }
    catch {
        Write-Host "Error during folder comparison: $_" -ForegroundColor Red
        return $null
    }
}

function Generate-FileHash {
    if ([string]::IsNullOrEmpty($global:sourcePath)) {
        Write-Host "Please set the source path first." -ForegroundColor Red
        return
    }

    Write-Host "`nGenerating File Hash..." -ForegroundColor Yellow
    try {
        $hash = Get-FileHash -Path $global:sourcePath -Algorithm SHA256
        $hash | Format-List
        return $hash
    }
    catch {
        Write-Host "Error generating file hash: $_" -ForegroundColor Red
        return $null
    }
}

function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File and Folder Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>File and Folder Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>Source Path: $global:sourcePath</p>
    <p>Destination Path: $global:destinationPath</p>

    <h2>Folder Structure Analysis</h2>
    $($AllResults.FolderAnalysis | ConvertTo-Html -Fragment)

    <h2>File Search Results</h2>
    $($AllResults.FileSearch | ConvertTo-Html -Fragment)

    <h2>Folder Comparison</h2>
    $($AllResults.FolderComparison | ConvertTo-Html -Fragment)

    <h2>File Hash</h2>
    $($AllResults.FileHash | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-12)"

    switch ($choice) {
        "1" { Set-SourcePath }
        "2" { Set-DestinationPath }
        "3" { Copy-FilesAndFolders }
        "4" { Move-FilesAndFolders }
        "5" { Delete-FilesAndFolders }
        "6" { Rename-FilesAndFolders }
        "7" { $allResults.FolderAnalysis = Analyze-FolderStructure }
        "8" { $allResults.FileSearch = Search-Files }
        "9" { $allResults.FolderComparison = Compare-Folders }
        "10" { $allResults.FileHash = Generate-FileHash }
        "11" { Generate-HTMLReport -AllResults $allResults }
        "12" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "12") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "12")

This File and Folder Manipulation Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to perform various file and folder operations:
    • Setting source and destination paths
    • Copying files and folders
    • Moving files and folders
    • Deleting files and folders
    • Renaming files and folders
    • Analyzing folder structure
    • Searching for files
    • Comparing folders
    • Generating file hashes
  3. HTML report generation for easy sharing and viewing of results.

Key features:

  • Flexible path setting for source and destination
  • Basic file operations (copy, move, delete, rename)
  • Folder structure analysis with file count and total size
  • File search functionality with wildcard support
  • Folder comparison to identify differences
  • File hash generation for integrity checking
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • System administrators managing file systems
  • IT professionals performing file and folder operations in bulk
  • Anyone needing to analyze, compare, or manipulate file structures

To use this script effectively:

  1. Run PowerShell with appropriate permissions to access and modify the file system
  2. Set the source and destination paths before performing operations
  3. Use caution with delete operations, as they are irreversible
  4. Review the generated HTML report for a comprehensive overview of the analysis results

This script provides a versatile set of tools for file and folder manipulation and analysis, helping users to efficiently manage and understand their file systems. It’s designed to be user-friendly while offering powerful functionality for both simple and complex file operations.

File and Folder Manipulation

File Manipulation

OperationPowerShell CommandDescription
Create a fileNew-Item -Path "path\filename.txt" -ItemType FileCreates a new file at the specified path
Copy a fileCopy-Item "source\file.txt" -Destination "dest\file.txt"Copies a file from source to destination
Move a fileMove-Item "source\file.txt" -Destination "dest\file.txt"Moves a file from source to destination
Rename a fileRename-Item "oldname.txt" -NewName "newname.txt"Renames a file
Delete a fileRemove-Item "path\filename.txt"Deletes the specified file
Read file contentGet-Content "path\filename.txt"Displays the content of a file
Write to a fileSet-Content "path\filename.txt" -Value "Text to write"Writes content to a file (overwrites existing content)
Append to a fileAdd-Content "path\filename.txt" -Value "Text to append"Appends content to the end of a file
Test if file existsTest-Path "path\filename.txt"Returns True if the file exists, False otherwise
Get file propertiesGet-ItemProperty "path\filename.txt"Retrieves the properties of a file
Set file attributesSet-ItemProperty "path\filename.txt" -Name Attributes -Value ReadOnlySets file attributes (e.g., ReadOnly, Hidden)
Get file hashGet-FileHash "path\filename.txt"Computes the hash of a file
Compare filesCompare-Object (Get-Content "file1.txt") (Get-Content "file2.txt")Compares the content of two files
Replace “path\filename.txt” with the actual path and filename you’re working with. Also, be cautious when using commands that modify or delete files, especially in production environments.

Folder Manipulation

OperationPowerShell CommandDescription
Create FolderNew-Item -Path "C:\Path\NewFolder" -ItemType DirectoryCreates a new folder at the specified path
Delete FolderRemove-Item -Path "C:\Path\FolderToDelete" -RecurseDeletes a folder and its contents
Copy FolderCopy-Item -Path "C:\SourceFolder" -Destination "C:\DestinationFolder" -RecurseCopies a folder and its contents to a new location
Move FolderMove-Item -Path "C:\SourceFolder" -Destination "C:\DestinationFolder"Moves a folder to a new location
Rename FolderRename-Item -Path "C:\OldFolderName" -NewName "NewFolderName"Renames a folder
Get Folder ContentsGet-ChildItem -Path "C:\FolderPath"Lists the contents of a folder
Get Folder Size`(Get-ChildItem -Path “C:\FolderPath” -RecurseMeasure-Object -Property Length -Sum).Sum`
Check if Folder ExistsTest-Path -Path "C:\FolderPath"Checks if a folder exists at the specified path
Get Folder PermissionsGet-Acl -Path "C:\FolderPath"Retrieves the access control list (ACL) for a folder
Set Folder PermissionsSet-Acl -Path "C:\FolderPath" -AclObject $AclSets the ACL for a folder (requires $Acl object)
Create JunctionNew-Item -ItemType Junction -Path "C:\JunctionPoint" -Target "C:\TargetFolder"Creates a junction point (symbolic link) to a folder
Replace the example paths (“C:\Path…”) with the actual paths you want to work with. Also, be cautious when using delete and move operations, as they can permanently affect your file system.