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.

Error Handling in PowerShell

PowerShell is a powerful scripting language that includes robust error handling capabilities. Effective error handling ensures that your scripts can gracefully handle unexpected situations, making them more reliable, maintainable, and easier to debug. This guide provides a detailed overview of various error handling techniques in PowerShell, including basic error management, advanced techniques, and best practices.

1. Basic Error Handling

1.1. Understanding ErrorAction

PowerShell cmdlets have a common parameter called -ErrorAction, which controls how they respond to non-terminating errors. The possible values are:

  • Continue (default): Displays the error and continues execution.
  • Stop: Treats the error as terminating, triggering the catch block in a Try-Catch.
  • SilentlyContinue: Suppresses the error message and continues execution.
  • Inquire: Prompts the user for input on how to proceed.
  • Ignore: Suppresses the error message and does not add it to the $Error automatic variable.

Example:

Get-Process -Name "NonExistentProcess" -ErrorAction SilentlyContinue

1.2. $ErrorActionPreference

This variable sets the default action for all errors in the script or session. It can be set to the same values as -ErrorAction.

Example:

$ErrorActionPreference = "Stop"

2. Advanced Error Handling

2.1. Try-Catch-Finally

The Try-Catch-Finally construct allows you to handle errors more granely. The Try block contains code that might fail, the Catch block handles the error, and the Finally block executes code regardless of whether an error occurred.

Syntax:

try {
    # Code that might throw an error
}
catch {
    # Code to handle the error
}
finally {
    # Code that runs regardless of an error
}

Example:

try {
    $content = Get-Content -Path "C:\nonexistentfile.txt"
}
catch {
    Write-Error "An error occurred: $_"
}
finally {
    Write-Output "This runs no matter what."
}

2.2. Catch Specific Exceptions

You can catch specific exceptions by specifying the exception type in the Catch block.

Example:

try {
    $content = Get-Content -Path "C:\nonexistentfile.txt"
}
catch [System.IO.FileNotFoundException] {
    Write-Error "File not found."
}
catch {
    Write-Error "An unexpected error occurred: $_"
}

2.3. Throwing Exceptions

You can generate your own errors using the throw keyword. This is useful for enforcing certain conditions within your script.

Example:

function Get-Data {
    param ($value)
    if (-not $value) {
        throw "Value cannot be null or empty."
    }
    return $value
}

try {
    Get-Data $null
}
catch {
    Write-Error "Caught an exception: $_"
}

3. Error Logging and Debugging

3.1. Using $Error Automatic Variable

The $Error variable is an array that stores the errors encountered in the current session. $Error[0] always contains the most recent error.

Example:

Get-Process -Name "NonExistentProcess" -ErrorAction SilentlyContinue
Write-Output $Error[0]

3.2. ErrorVariable Parameter

Use the -ErrorVariable parameter to capture errors in a custom variable, separate from $Error.

Example:

Get-Process -Name "NonExistentProcess" -ErrorVariable myError
Write-Output $myError

3.3. Logging Errors

Errors can be logged to a file for later review, which is particularly useful in production scripts.

Example:

try {
    Get-Content -Path "C:\nonexistentfile.txt"
}
catch {
    $errorMessage = "$(Get-Date): Error: $_"
    Add-Content -Path "C:\logs\error.log" -Value $errorMessage
}

3.4. Verbose and Debug Output

PowerShell provides Write-Verbose and Write-Debug for logging detailed information and debugging output, which can be enabled using the -Verbose and -Debug parameters.

Example:

function Get-Info {
    [CmdletBinding()]
    param ($path)
    
    Write-Verbose "Checking file at $path"
    
    try {
        $content = Get-Content -Path $path
        Write-Output $content
    }
    catch {
        Write-Debug "Error reading file: $_"
        throw
    }
}

Get-Info -path "C:\nonexistentfile.txt" -Verbose -Debug

4. Best Practices for Error Handling

4.1. Always Use Try-Catch for Critical Operations

Whenever you’re performing operations that can fail, such as file operations, network calls, or system changes, wrap them in Try-Catch blocks.

4.2. Handle Errors Gracefully

Provide meaningful error messages and handle errors in a way that doesn’t disrupt the entire script. Consider logging errors and providing alternatives or fallback actions.

4.3. Validate Inputs

Before processing data, validate inputs to avoid unnecessary errors. This can be done using ValidateNotNullOrEmpty, ValidateRange, and other validation attributes in your function parameters.

Example:

function Get-Data {
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$filePath
    )
    
    try {
        $content = Get-Content -Path $filePath
        return $content
    }
    catch {
        Write-Error "An error occurred while reading the file: $_"
    }
}

4.4. Use ErrorAction and ErrorVariable Appropriately

Use -ErrorAction and -ErrorVariable to manage and store errors locally, especially in larger scripts where you want to handle errors in specific ways without affecting global error handling.

4.5. Test Error Scenarios

Simulate errors in your scripts to ensure that your error handling code works as expected. This includes testing with missing files, incorrect permissions, network timeouts, etc.

4.6. Log Errors for Auditing

In production environments, logging is crucial. Ensure that all critical errors are logged with sufficient detail to facilitate debugging and audits.

4.7. Use $PSCmdlet.ThrowTerminatingError() for Cmdlets

When writing advanced functions or cmdlets, use $PSCmdlet.ThrowTerminatingError() to throw errors in a way that is consistent with PowerShell cmdlets.

Example:

function Invoke-CustomCmdlet {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]$input
    )
    
    if ($null -eq $input) {
        $errorRecord = New-Object System.Management.Automation.ErrorRecord -ArgumentList ("Input cannot be null", "InputError", [System.Management.Automation.ErrorCategory]::InvalidArgument, $input)
        $PSCmdlet.ThrowTerminatingError($errorRecord)
    }
    
    Write-Output "Input is valid"
}

Effective error handling in PowerShell is crucial for building robust and reliable scripts. By using the techniques outlined in this guide, such as Try-Catch-Finally, logging, and custom error handling, you can ensure that your scripts handle errors gracefully and provide useful feedback for debugging and maintenance. Whether you’re writing simple scripts or complex automation workflows, integrating these best practices will help you create PowerShell scripts that are resilient and maintainable.

Script Template for PowerShell

<#
.SYNOPSIS
    Brief description of what the script does.

.DESCRIPTION
    Detailed description of the script's purpose and functionality.

.PARAMETER ParamName1
    Description of the first parameter.

.PARAMETER ParamName2
    Description of the second parameter.

.EXAMPLE
    Example-1: .\ScriptName.ps1 -ParamName1 Value1 -ParamName2 Value2
    Description of what this example does.

.EXAMPLE
    Example-2: .\ScriptName.ps1 -ParamName1 Value3
    Description of what this example does.

.NOTES
    File Name      : ScriptName.ps1
    Author         : Your Name
    Prerequisite   : PowerShell V3 or later
    Copyright      : (c) 2023 Your Company. All rights reserved.

.LINK
    Script posted over:
    http://www.your-website.com

#>

#Requires -Version 3.0
#Requires -Modules ActiveDirectory, Exchange
#Requires -RunAsAdministrator

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true, 
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true, 
               ValueFromRemainingArguments=$false, 
               Position=0,
               HelpMessage="Enter the first parameter value.")]
    [ValidateNotNullOrEmpty()]
    [Alias("PN1")]
    [string]$ParamName1,

    [Parameter(Mandatory=$false)]
    [int]$ParamName2 = 0
)

Begin {
    # Initialize variables, import modules, define functions
    Set-StrictMode -Version Latest
    $ErrorActionPreference = "Stop"

    # Log file setup
    $LogFile = "C:\Logs\ScriptName_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
    
    function Write-Log {
        param([string]$Message)
        $LogMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'): $Message"
        Add-Content -Path $LogFile -Value $LogMessage
        Write-Verbose $LogMessage
    }

    Write-Log "Script started"
}

Process {
    try {
        # Main script logic goes here
        Write-Log "Processing started"

        # Your code here

        Write-Log "Processing completed"
    }
    catch {
        Write-Log "An error occurred: $_"
        throw $_
    }
}

End {
    # Cleanup operations
    Write-Log "Script completed"
}

This template includes:

  1. A comprehensive comment-based help section at the beginning, which provides information about the script’s purpose, parameters, examples, and more.
  2. #Requires statements to specify prerequisites like PowerShell version, required modules, or administrator rights.
  3. [CmdletBinding()] attribute to make the script behave like a cmdlet.
  4. Parameter block with examples of mandatory and optional parameters, including parameter attributes.
  5. Begin, Process, and End blocks to structure the script’s execution.
  6. Error handling with try-catch blocks.
  7. Logging functionality to keep track of the script’s execution.
  8. Use of Set-StrictMode and $ErrorActionPreference for better error detection and handling.

You can customize this template based on your specific needs, adding or removing sections as necessary for your script.

Email Validation Toolkit

# Email Validation Toolkit

# Function to validate email using a simple regex pattern
function Test-EmailSimple {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Email
    )
    
    $regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    return $Email -match $regex
}

# Function to validate email using a more comprehensive regex pattern
function Test-EmailComprehensive {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Email
    )
    
    $regex = "^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"
    return $Email -match $regex
}

# Function to validate email with domain check
function Test-EmailWithDomain {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Email
    )
    
    $regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    if ($Email -match $regex) {
        $domain = ($Email -split "@")[1]
        if (Resolve-DnsName -Name $domain -ErrorAction SilentlyContinue) {
            return $true
        }
    }
    return $false
}

# Function to validate multiple emails
function Test-MultipleEmails {
    param (
        [Parameter(Mandatory=$true)]
        [string[]]$Emails,
        [Parameter(Mandatory=$false)]
        [ValidateSet("Simple", "Comprehensive", "WithDomain")]
        [string]$Method = "Simple"
    )
    
    $results = @()
    foreach ($email in $Emails) {
        switch ($Method) {
            "Simple" { $isValid = Test-EmailSimple -Email $email }
            "Comprehensive" { $isValid = Test-EmailComprehensive -Email $email }
            "WithDomain" { $isValid = Test-EmailWithDomain -Email $email }
        }
        $results += [PSCustomObject]@{
            Email = $email
            IsValid = $isValid
        }
    }
    return $results
}

# Function to extract emails from text
function Get-EmailsFromText {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Text
    )
    
    $regex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
    return $Text | Select-String -Pattern $regex -AllMatches | ForEach-Object { $_.Matches.Value }
}

# Example usage
$testEmails = @(
    "user@example.com",
    "invalid.email@",
    "another.user@example.co.uk",
    "not_an_email"
)

Write-Host "Simple Validation:"
Test-MultipleEmails -Emails $testEmails -Method Simple | Format-Table

Write-Host "`nComprehensive Validation:"
Test-MultipleEmails -Emails $testEmails -Method Comprehensive | Format-Table

Write-Host "`nValidation with Domain Check:"
Test-MultipleEmails -Emails $testEmails -Method WithDomain | Format-Table

$sampleText = "Contact us at support@example.com or sales@company.co.uk for more information."
Write-Host "`nExtracting emails from text:"
Get-EmailsFromText -Text $sampleText

This toolkit includes the following functions:

  1. Test-EmailSimple: Uses a simple regex pattern to validate email addresses.
  2. Test-EmailComprehensive: Uses a more comprehensive regex pattern for stricter validation.
  3. Test-EmailWithDomain: Validates the email format and checks if the domain exists.
  4. Test-MultipleEmails: Validates multiple email addresses using one of the above methods.
  5. Get-EmailsFromText: Extracts email addresses from a given text.

To use this toolkit, you can copy and paste the entire script into a PowerShell file (e.g., EmailValidationToolkit.ps1) and then dot-source it in your PowerShell session:

. .\EmailValidationToolkit.ps1

PowerShell Toolkit for Regex IP Networking

# PowerShell Toolkit for Regex IP Networking

# Function to validate an IPv4 address
function Test-IPv4Address {
    param (
        [Parameter(Mandatory=$true)]
        [string]$IPAddress
    )
    
    $regex = '^\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b$'
    return $IPAddress -match $regex
}

# Function to validate an IPv6 address
function Test-IPv6Address {
    param (
        [Parameter(Mandatory=$true)]
        [string]$IPAddress
    )
    
    $regex = '^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$'
    return $IPAddress -match $regex
}

# Function to extract all IPv4 addresses from a string
function Get-IPv4Addresses {
    param (
        [Parameter(Mandatory=$true)]
        [string]$InputString
    )
    
    $regex = '\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
    return $InputString | Select-String -Pattern $regex -AllMatches | ForEach-Object { $_.Matches.Value }
}

# Function to extract all IPv6 addresses from a string
function Get-IPv6Addresses {
    param (
        [Parameter(Mandatory=$true)]
        [string]$InputString
    )
    
    $regex = '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))'
    return $InputString | Select-String -Pattern $regex -AllMatches | ForEach-Object { $_.Matches.Value }
}

# Function to validate a subnet mask
function Test-SubnetMask {
    param (
        [Parameter(Mandatory=$true)]
        [string]$SubnetMask
    )
    
    $regex = '^(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))$'
    return $SubnetMask -match $regex
}

# Function to validate CIDR notation
function Test-CIDRNotation {
    param (
        [Parameter(Mandatory=$true)]
        [string]$CIDR
    )
    
    $regex = '^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))$'
    return $CIDR -match $regex
}

# Function to extract network address from CIDR notation
function Get-NetworkAddress {
    param (
        [Parameter(Mandatory=$true)]
        [string]$CIDR
    )
    
    if (Test-CIDRNotation $CIDR) {
        $parts = $CIDR -split '/'
        $ip = $parts[0]
        $mask = [int]$parts[1]
        
        $ipBytes = [System.Net.IPAddress]::Parse($ip).GetAddressBytes()
        $maskBytes = [byte[]](,0xFF * 4)
        for ($i = 0; $i -lt 4; $i++) {
            if ($mask -lt 8) {
                $maskBytes[$i] = [byte]((0xFF -shl (8 - $mask)) -band 0xFF)
                $mask = 0
            } else {
                $mask -= 8
            }
        }
        
        $networkBytes = for ($i = 0; $i -lt 4; $i++) {
            $ipBytes[$i] -band $maskBytes[$i]
        }
        
        return [System.Net.IPAddress]($networkBytes)
    } else {
        Write-Error "Invalid CIDR notation"
        return $null
    }
}

# Example usage:
# Test-IPv4Address "192.168.1.1"
# Test-IPv6Address "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
# Get-IPv4Addresses "The IP addresses are 192.168.1.1 and 10.0.0.1"
# Get-IPv6Addresses "IPv6 addresses: 2001:0db8:85a3::8a2e:0370:7334 and fe80::1"
# Test-SubnetMask "255.255.255.0"
# Test-CIDRNotation "192.168.1.0/24"
# Get-NetworkAddress "192.168.1.100/24"

This toolkit provides the following functions:

  1. Test-IPv4Address: Validates an IPv4 address.
  2. Test-IPv6Address: Validates an IPv6 address.
  3. Get-IPv4Addresses: Extracts all IPv4 addresses from a given string.
  4. Get-IPv6Addresses: Extracts all IPv6 addresses from a given string.
  5. Test-SubnetMask: Validates a subnet mask.
  6. Test-CIDRNotation: Validates CIDR notation.
  7. Get-NetworkAddress: Extracts the network address from CIDR notation.

You can use these functions in your PowerShell scripts or directly in the PowerShell console. The example usage at the end of the script shows how to call each function.

Regular Expression (regex) in PowerShell

ElementDescriptionExample
.Matches any single character except newline“h.t” matches “hat”, “hot”, “hit”
*Matches zero or more occurrences of the previous character“a*b” matches “b”, “ab”, “aab”, “aaab”
+Matches one or more occurrences of the previous character“a+b” matches “ab”, “aab”, “aaab”, but not “b”
?Matches zero or one occurrence of the previous character“colou?r” matches “color” and “colour”
^Matches the start of a line“^Hello” matches “Hello World” but not “World Hello”
$Matches the end of a line“World$” matches “Hello World” but not “World Hello”
[ ]Matches any single character in brackets“[aeiou]” matches any vowel
[^ ]Matches any single character not in brackets“[^aeiou]” matches any consonant
( )Groups characters“(ab)+” matches “ab”, “abab”, “ababab”
|Alternation (OR)“cat|dog” matches “cat” or “dog”
{ }Specifies exact number of occurrences to match“a{3}” matches exactly three “a”s
\dMatches any digit“\d{3}” matches three digits
\DMatches any non-digit“\D+” matches one or more non-digits
\wMatches any word character (a-z, A-Z, 0-9, _)“\w+” matches one or more word characters
\WMatches any non-word character“\W” matches any single non-word character
\sMatches any whitespace character“\s” matches space, tab, newline
\SMatches any non-whitespace character“\S+” matches one or more non-whitespace characters
\bMatches a word boundary“\bword\b” matches “word” as a whole word
\BMatches a non-word boundary“\Bword\B” matches “word” only if it’s part of a larger word
(?i)Makes the match case-insensitive“(?i)hello” matches “hello”, “Hello”, “HELLO”
(?m)Enables multiline mode“(?m)^start” matches “start” at the beginning of any line
(?s)Enables single-line mode (dot matches newline)“(?s).*” matches everything including newlines
(?<name>…)Named capturing group“(?<year>\d{4})” captures a year in a named group
(?:…)Non-capturing group“(?:ab)+” matches “ab”, “abab” without creating a capture group
(?=…)Positive lookahead“Jacob(?=\sSm)” matches “Jacob” only if followed by ” Sm”
(?!…)Negative lookahead“Jacob(?!\sSm)” matches “Jacob” only if not followed by ” Sm”
(?<=…)Positive lookbehind“(?<=Mr.)\s\w+” matches a name if preceded by “Mr.”
(?<!…)Negative lookbehind“(?<!Mr.)\s\w+” matches a name if not preceded by “Mr.”

PowerShell Networking Cmdlets

CommandDescriptionExample
Get-NetAdapterRetrieves network adapter informationGet-NetAdapter
Get-NetIPAddressRetrieves IP address configurationGet-NetIPAddress
Get-NetRouteDisplays the IP routing tableGet-NetRoute
Test-NetConnectionTests network connectivity to a remote computerTest-NetConnection -ComputerName google.com
Resolve-DnsNamePerforms DNS name resolutionResolve-DnsName google.com
Get-DnsClientServerAddressRetrieves DNS server addressesGet-DnsClientServerAddress
Get-NetTCPConnectionDisplays active TCP connectionsGet-NetTCPConnection
Get-NetUDPEndpointDisplays active UDP endpointsGet-NetUDPEndpoint
Get-NetFirewallRuleRetrieves firewall rulesGet-NetFirewallRule
New-NetFirewallRuleCreates a new firewall ruleNew-NetFirewallRule -DisplayName “Allow Port 80” -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
Set-NetFirewallRuleModifies an existing firewall ruleSet-NetFirewallRule -DisplayName “Allow Port 80” -Enabled True
Remove-NetFirewallRuleRemoves a firewall ruleRemove-NetFirewallRule -DisplayName “Allow Port 80”
Get-NetIPConfigurationDisplays IP configuration for all network adaptersGet-NetIPConfiguration
Set-NetIPAddressModifies IP address settingsSet-NetIPAddress -InterfaceIndex 12 -IPAddress 192.168.1.100 -PrefixLength 24
New-NetIPAddressAdds a new IP address to an interfaceNew-NetIPAddress -InterfaceIndex 12 -IPAddress 192.168.1.100 -PrefixLength 24 -DefaultGateway 192.168.1.1
Remove-NetIPAddressRemoves an IP address from an interfaceRemove-NetIPAddress -InterfaceIndex 12 -IPAddress 192.168.1.100
Get-NetNeighborDisplays the Address Resolution Protocol (ARP) cacheGet-NetNeighbor
Clear-DnsClientCacheClears the DNS client cacheClear-DnsClientCache
Get-NetConnectionProfileRetrieves network connection profilesGet-NetConnectionProfile
Set-NetConnectionProfileSets properties of a network connection profileSet-NetConnectionProfile -InterfaceIndex 12 -NetworkCategory Private
Disable-NetAdapterDisables a network adapterDisable-NetAdapter -Name “Ethernet”
Enable-NetAdapterEnables a network adapterEnable-NetAdapter -Name “Ethernet”
Restart-NetAdapterRestarts a network adapterRestart-NetAdapter -Name “Ethernet”
Get-NetAdapterBindingRetrieves network adapter bindingsGet-NetAdapterBinding -Name “Ethernet”
Enable-NetAdapterBindingEnables a specific binding on a network adapterEnable-NetAdapterBinding -Name “Ethernet” -ComponentID ms_tcpip
Disable-NetAdapterBindingDisables a specific binding on a network adapterDisable-NetAdapterBinding -Name “Ethernet” -ComponentID ms_tcpip
This table covers a wide range of networking commands in PowerShell, from basic connectivity testing to more advanced configuration tasks. Remember to run PowerShell as an administrator for commands that modify system settings.

Active Directory Cmdlets

CommandDescriptionCommon Parameters
Get-ADUserRetrieves one or more Active Directory users-Identity, -Filter, -Properties, -SearchBase
New-ADUserCreates a new Active Directory user-Name, -SamAccountName, -UserPrincipalName, -Path
Set-ADUserModifies properties of an existing Active Directory user-Identity, -EmailAddress, -Enabled, -PasswordNeverExpires
Remove-ADUserRemoves an Active Directory user-Identity, -Confirm
Get-ADGroupRetrieves one or more Active Directory groups-Identity, -Filter, -Properties, -SearchBase
New-ADGroupCreates a new Active Directory group-Name, -GroupScope, -GroupCategory, -Path
Set-ADGroupModifies properties of an existing Active Directory group-Identity, -Description, -ManagedBy
Remove-ADGroupRemoves an Active Directory group-Identity, -Confirm
Add-ADGroupMemberAdds one or more members to an Active Directory group-Identity, -Members
Remove-ADGroupMemberRemoves one or more members from an Active Directory group-Identity, -Members, -Confirm
Get-ADComputerRetrieves one or more Active Directory computer objects-Identity, -Filter, -Properties, -SearchBase
New-ADComputerCreates a new Active Directory computer object-Name, -SAMAccountName, -Path
Set-ADComputerModifies properties of an existing Active Directory computer object-Identity, -Description, -Enabled
Remove-ADComputerRemoves an Active Directory computer object-Identity, -Confirm
Get-ADOrganizationalUnitRetrieves one or more Active Directory organizational units-Identity, -Filter, -Properties, -SearchBase
New-ADOrganizationalUnitCreates a new Active Directory organizational unit-Name, -Path
Set-ADOrganizationalUnitModifies properties of an existing Active Directory organizational unit-Identity, -Description, -ProtectedFromAccidentalDeletion
Remove-ADOrganizationalUnitRemoves an Active Directory organizational unit-Identity, -Confirm
Get-ADDomainRetrieves information about the current or specified Active Directory domain-Identity, -Server
Get-ADForestRetrieves information about the current or specified Active Directory forest-Identity, -Server
Get-ADDomainControllerRetrieves one or more Active Directory domain controllers-Identity, -Filter, -Server
Move-ADObjectMoves an Active Directory object from one container to another-Identity, -TargetPath
Rename-ADObjectRenames an Active Directory object-Identity, -NewName
Set-ADAccountPasswordSets the password of an Active Directory account-Identity, -NewPassword, -Reset
Unlock-ADAccountUnlocks an Active Directory account-Identity
Enable-ADAccountEnables an Active Directory account-Identity
Disable-ADAccountDisables an Active Directory account-Identity
Get-ADGroupMemberRetrieves members of an Active Directory group-Identity, -Recursive
Search-ADAccountSearches for Active Directory accounts based on specific criteria-AccountDisabled, -AccountExpired, -AccountInactive, -PasswordExpired
This table covers the most commonly used Active Directory cmdlets in PowerShell. There are additional cmdlets and parameters available for more specific tasks. Always refer to the official Microsoft documentation for the most up-to-date and complete information on Active Directory PowerShell cmdlets.