Tag Archive for: Toolkit

Web Server Security Toolkit

<#
.SYNOPSIS
Web Server Security Toolkit

.DESCRIPTION
This script provides a comprehensive set of tools for analyzing and enhancing the security of web servers,
with a focus on IIS (Internet Information Services).

.NOTES
File Name      : WebServerSecurityToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights, IIS installed
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\WebServerSecurityToolkit.ps1
#>

# Import required modules
Import-Module WebAdministration
Import-Module IISAdministration

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

function Show-Menu {
    Clear-Host
    Write-Host "=== Web Server Security Toolkit ===" -ForegroundColor Cyan
    Write-Host "1.  Analyze IIS Configuration"
    Write-Host "2.  Check SSL/TLS Configuration"
    Write-Host "3.  Review Web Application Firewall (WAF) Settings"
    Write-Host "4.  Analyze HTTP Response Headers"
    Write-Host "5.  Check File and Folder Permissions"
    Write-Host "6.  Review Application Pool Settings"
    Write-Host "7.  Analyze Logging and Auditing Configuration"
    Write-Host "8.  Check for Unnecessary Services and Features"
    Write-Host "9.  Review Authentication Methods"
    Write-Host "10. Analyze Network Security Settings"
    Write-Host "11. Check for Common Vulnerabilities"
    Write-Host "12. Generate Comprehensive HTML Report"
    Write-Host "13. Exit"
}

function Analyze-IISConfiguration {
    Write-Host "`nAnalyzing IIS Configuration..." -ForegroundColor Yellow
    try {
        $iisVersion = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\InetStp"
        $websites = Get-Website
        $appPools = Get-IISAppPool

        $result = [PSCustomObject]@{
            IISVersion = "$($iisVersion.MajorVersion).$($iisVersion.MinorVersion)"
            WebsitesCount = $websites.Count
            AppPoolsCount = $appPools.Count
            DefaultWebsiteEnabled = (Get-Website "Default Web Site").State -eq "Started"
        }

        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error analyzing IIS configuration: $_" -ForegroundColor Red
        return $null
    }
}

function Check-SSLTLSConfiguration {
    Write-Host "`nChecking SSL/TLS Configuration..." -ForegroundColor Yellow
    try {
        $sslProtocols = @("SSL 2.0", "SSL 3.0", "TLS 1.0", "TLS 1.1", "TLS 1.2")
        $results = @()

        foreach ($protocol in $sslProtocols) {
            $clientPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\$protocol\Client"
            $serverPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\$protocol\Server"
            
            $clientEnabled = (Get-ItemProperty -Path $clientPath -Name "Enabled" -ErrorAction SilentlyContinue).Enabled
            $serverEnabled = (Get-ItemProperty -Path $serverPath -Name "Enabled" -ErrorAction SilentlyContinue).Enabled

            $results += [PSCustomObject]@{
                Protocol = $protocol
                ClientEnabled = if ($clientEnabled -eq 0) { "Disabled" } elseif ($clientEnabled -eq 1) { "Enabled" } else { "Not Configured" }
                ServerEnabled = if ($serverEnabled -eq 0) { "Disabled" } elseif ($serverEnabled -eq 1) { "Enabled" } else { "Not Configured" }
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error checking SSL/TLS configuration: $_" -ForegroundColor Red
        return $null
    }
}

function Review-WAFSettings {
    Write-Host "`nReviewing Web Application Firewall (WAF) Settings..." -ForegroundColor Yellow
    Write-Host "Note: This function checks for common WAF solutions. Actual WAF may vary." -ForegroundColor Yellow
    
    try {
        $wafPresent = $false
        $wafInfo = [PSCustomObject]@{
            WAFDetected = $false
            WAFType = "Unknown"
            Status = "Not Installed"
        }

        # Check for common WAF solutions (this is a simplified check and may need to be adapted)
        if (Get-Service "MicrosoftAzureApplicationGateway" -ErrorAction SilentlyContinue) {
            $wafPresent = $true
            $wafInfo.WAFDetected = $true
            $wafInfo.WAFType = "Azure Application Gateway"
            $wafInfo.Status = "Installed"
        }
        elseif (Get-Website "ARR_*" -ErrorAction SilentlyContinue) {
            $wafPresent = $true
            $wafInfo.WAFDetected = $true
            $wafInfo.WAFType = "Application Request Routing (Potential WAF)"
            $wafInfo.Status = "Installed"
        }

        if (-not $wafPresent) {
            Write-Host "No common WAF solution detected. Manual verification recommended." -ForegroundColor Yellow
        }

        $wafInfo | Format-List
        return $wafInfo
    }
    catch {
        Write-Host "Error reviewing WAF settings: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-HTTPResponseHeaders {
    Write-Host "`nAnalyzing HTTP Response Headers..." -ForegroundColor Yellow
    try {
        $websites = Get-Website
        $results = @()

        foreach ($site in $websites) {
            $headers = Get-WebConfiguration "/system.webServer/httpProtocol/customHeaders" -PSPath "IIS:\Sites\$($site.Name)"
            $securityHeaders = @(
                "X-Frame-Options",
                "X-XSS-Protection",
                "X-Content-Type-Options",
                "Strict-Transport-Security",
                "Content-Security-Policy",
                "Referrer-Policy"
            )

            $presentHeaders = $headers.Collection | Where-Object { $securityHeaders -contains $_.Name } | Select-Object Name, Value

            $results += [PSCustomObject]@{
                Website = $site.Name
                PresentSecurityHeaders = ($presentHeaders | ForEach-Object { "$($_.Name): $($_.Value)" }) -join ", "
                MissingSecurityHeaders = ($securityHeaders | Where-Object { $_ -notin $presentHeaders.Name }) -join ", "
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error analyzing HTTP response headers: $_" -ForegroundColor Red
        return $null
    }
}

function Check-FileAndFolderPermissions {
    Write-Host "`nChecking File and Folder Permissions..." -ForegroundColor Yellow
    try {
        $websites = Get-Website
        $results = @()

        foreach ($site in $websites) {
            $physicalPath = $site.PhysicalPath -replace "%SystemDrive%", $env:SystemDrive
            $acl = Get-Acl $physicalPath
            $permissions = $acl.Access | Select-Object IdentityReference, FileSystemRights

            $results += [PSCustomObject]@{
                Website = $site.Name
                PhysicalPath = $physicalPath
                Permissions = ($permissions | ForEach-Object { "$($_.IdentityReference): $($_.FileSystemRights)" }) -join "; "
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error checking file and folder permissions: $_" -ForegroundColor Red
        return $null
    }
}

function Review-ApplicationPoolSettings {
    Write-Host "`nReviewing Application Pool Settings..." -ForegroundColor Yellow
    try {
        $appPools = Get-IISAppPool
        $results = @()

        foreach ($pool in $appPools) {
            $results += [PSCustomObject]@{
                Name = $pool.Name
                ManagedRuntimeVersion = $pool.ManagedRuntimeVersion
                IdentityType = $pool.ProcessModel.IdentityType
                IdleTimeout = $pool.ProcessModel.IdleTimeout
                LoadUserProfile = $pool.ProcessModel.LoadUserProfile
                MaxProcesses = $pool.ProcessModel.MaxProcesses
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error reviewing application pool settings: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-LoggingAndAuditingConfiguration {
    Write-Host "`nAnalyzing Logging and Auditing Configuration..." -ForegroundColor Yellow
    try {
        $websites = Get-Website
        $results = @()

        foreach ($site in $websites) {
            $logFile = Get-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST/$($site.Name)"  -filter "system.applicationHost/sites/site[@name='$($site.Name)']/logFile" -name *
            
            $results += [PSCustomObject]@{
                Website = $site.Name
                LoggingEnabled = $logFile.enabled
                LogFormat = $logFile.logFormat
                Directory = $logFile.directory
                Period = $logFile.period
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error analyzing logging and auditing configuration: $_" -ForegroundColor Red
        return $null
    }
}

function Check-UnnecessaryServicesAndFeatures {
    Write-Host "`nChecking for Unnecessary Services and Features..." -ForegroundColor Yellow
    try {
        $unnecessaryFeatures = @(
            "IIS-WebDAV",
            "IIS-ASPNET45",
            "IIS-ASP",
            "IIS-CGI",
            "IIS-ServerSideIncludes"
        )

        $installedFeatures = Get-WindowsOptionalFeature -Online | Where-Object { $_.State -eq "Enabled" }
        $results = @()

        foreach ($feature in $unnecessaryFeatures) {
            $installed = $installedFeatures | Where-Object { $_.FeatureName -eq $feature }
            $results += [PSCustomObject]@{
                Feature = $feature
                Installed = if ($installed) { $true } else { $false }
                Recommendation = if ($installed) { "Consider removing if not needed" } else { "Not installed (Good)" }
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error checking unnecessary services and features: $_" -ForegroundColor Red
        return $null
    }
}

function Review-AuthenticationMethods {
    Write-Host "`nReviewing Authentication Methods..." -ForegroundColor Yellow
    try {
        $websites = Get-Website
        $results = @()

        foreach ($site in $websites) {
            $authMethods = @(
                "anonymousAuthentication",
                "basicAuthentication",
                "windowsAuthentication",
                "digestAuthentication"
            )

            $enabledMethods = @()

            foreach ($method in $authMethods) {
                $config = Get-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST/$($site.Name)"  -filter "system.webServer/security/authentication/$method" -name "enabled"
                if ($config.Value) {
                    $enabledMethods += $method
                }
            }

            $results += [PSCustomObject]@{
                Website = $site.Name
                EnabledAuthMethods = $enabledMethods -join ", "
            }
        }

        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error reviewing authentication methods: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-NetworkSecuritySettings {
    Write-Host "`nAnalyzing Network Security Settings..." -ForegroundColor Yellow
    try {
        $firewallRules = Get-NetFirewallRule | Where-Object { $_.Enabled -and ($_.Direction -eq "Inbound") }
        $openPorts = Get-NetTCPConnection | Where-Object { $_.State -eq "Listen" } | Select-Object LocalPort -Unique

        $results = [PSCustomObject]@{
            FirewallRulesCount = $firewallRules.Count
            OpenPorts = ($openPorts.LocalPort | Sort-Object) -join ", "
        }

        $results | Format-List
        return $results
    }
    catch {
        Write-Host "Error analyzing network security settings: $_" -ForegroundColor Red
        return $null
    }
}

function Check-CommonVulnerabilities {
    Write-Host "`nChecking for Common Vulnerabilities..." -ForegroundColor Yellow
    try {
        $vulnerabilities = @()

        # Check for directory browsing
        $dirBrowsing = Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.webServer/directoryBrowse" -name "enabled"
        if ($dirBrowsing.Value) {
            $vulnerabilities += "Directory browsing is enabled"
        }

        # Check for potentially dangerous HTTP methods
        $webDAV = Get-WindowsOptionalFeature -Online -FeatureName IIS-WebDAV
        if ($webDAV.State -eq "Enabled") {
            $vulnerabilities += "WebDAV is enabled, which allows potentially dangerous HTTP methods"
        }

        # Check for default documents
        $defaultDocs = Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.webServer/defaultDocument/files/add" -name "value"
        if ($defaultDocs.Value -contains "iisstart.htm") {
            $vulnerabilities += "Default IIS start page is present"
        }

        if ($vulnerabilities.Count -eq 0) {
            Write-Host "No common vulnerabilities detected." -ForegroundColor Green
        } else {
            Write-Host "Vulnerabilities detected:" -ForegroundColor Red
            $vulnerabilities | ForEach-Object { Write-Host "- $_" -ForegroundColor Yellow }
        }

        return $vulnerabilities
    }
    catch {
        Write-Host "Error checking for common vulnerabilities: $_" -ForegroundColor Red
        return $null
    }
}

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>Web Server Security 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; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>Web Server Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>IIS Configuration</h2>
    $($AllResults.IISConfig | ConvertTo-Html -Fragment)

    <h2>SSL/TLS Configuration</h2>
    $($AllResults.SSLTLSConfig | ConvertTo-Html -Fragment)

    <h2>WAF Settings</h2>
    $($AllResults.WAFSettings | ConvertTo-Html -Fragment)

    <h2>HTTP Response Headers</h2>
    $($AllResults.HTTPHeaders | ConvertTo-Html -Fragment)

    <h2>File and Folder Permissions</h2>
    $($AllResults.Permissions | ConvertTo-Html -Fragment)

    <h2>Application Pool Settings</h2>
    $($AllResults.AppPoolSettings | ConvertTo-Html -Fragment)

    <h2>Logging and Auditing Configuration</h2>
    $($AllResults.LoggingConfig | ConvertTo-Html -Fragment)

    <h2>Unnecessary Services and Features</h2>
    $($AllResults.UnnecessaryFeatures | ConvertTo-Html -Fragment)

    <h2>Authentication Methods</h2>
    $($AllResults.AuthMethods | ConvertTo-Html -Fragment)

    <h2>Network Security Settings</h2>
    $($AllResults.NetworkSecurity | ConvertTo-Html -Fragment)

    <h2>Common Vulnerabilities</h2>
    $($AllResults.Vulnerabilities | 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-13)"

    switch ($choice) {
        "1"  { $allResults.IISConfig = Analyze-IISConfiguration }
        "2"  { $allResults.SSLTLSConfig = Check-SSLTLSConfiguration }
        "3"  { $allResults.WAFSettings = Review-WAFSettings }
        "4"  { $allResults.HTTPHeaders = Analyze-HTTPResponseHeaders }
        "5"  { $allResults.Permissions = Check-FileAndFolderPermissions }
        "6"  { $allResults.AppPoolSettings = Review-ApplicationPoolSettings }
        "7"  { $allResults.LoggingConfig = Analyze-LoggingAndAuditingConfiguration }
        "8"  { $allResults.UnnecessaryFeatures = Check-UnnecessaryServicesAndFeatures }
        "9"  { $allResults.AuthMethods = Review-AuthenticationMethods }
        "10" { $allResults.NetworkSecurity = Analyze-NetworkSecuritySettings }
        "11" { $allResults.Vulnerabilities = Check-CommonVulnerabilities }
        "12" { Generate-HTMLReport -AllResults $allResults }
        "13" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Web Server Security Toolkit includes:

  1. A comprehensive menu-driven interface.
  2. Functions to analyze various aspects of web server security:
    • IIS Configuration Analysis
    • SSL/TLS Configuration Check
    • Web Application Firewall (WAF) Settings Review
    • HTTP Response Headers Analysis
    • File and Folder Permissions Check
    • Application Pool Settings Review
    • Logging and Auditing Configuration Analysis
    • Check for Unnecessary Services and Features
    • Authentication Methods Review
    • Network Security Settings Analysis
    • Common Vulnerabilities Check
  3. Comprehensive HTML report generation.

Key features:

  • Detailed analysis of IIS configuration and settings
  • SSL/TLS protocol and cipher suite checks
  • WAF detection and configuration review
  • Security-related HTTP header analysis
  • File system permissions audit for web directories
  • Application pool security configuration review
  • Logging and auditing settings analysis
  • Identification of potentially unnecessary or risky IIS features
  • Authentication method review across websites
  • Network security analysis including firewall rules and open ports
  • Common web server vulnerability checks
  • Comprehensive HTML report for all analyses

This tool is particularly useful for:

  • Web server administrators
  • Security professionals auditing web server configurations
  • IT professionals setting up or maintaining IIS servers
  • Anyone needing to assess the security posture of a web server

To use this script effectively:

  1. Run PowerShell as an administrator on the web server
  2. Ensure you have the necessary permissions to query IIS and system configurations
  3. Have the IIS PowerShell modules installed (WebAdministration and IISAdministration)
  4. Review the generated HTML report for a comprehensive overview of the web server’s security configuration

This script provides a thorough analysis of web server security settings, helping to identify potential vulnerabilities, misconfigurations, or areas for improvement in the server’s security posture. It’s designed to give administrators a comprehensive view of their web server’s security configuration and highlight areas that may need attention.

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.

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.

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.

RDS License Audit Toolkit

<#
.SYNOPSIS
RDS License Audit Toolkit

.DESCRIPTION
This script performs a comprehensive audit of Remote Desktop Services (RDS) licensing,
including license server configuration, available licenses, and usage statistics.

.NOTES
File Name      : RDSLicenseAuditToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights, and RDS management tools
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\RDSLicenseAuditToolkit.ps1
#>

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\RDS_License_Audit_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
$global:licenseServer = $env:COMPUTERNAME  # Default to local machine

function Show-Menu {
    Clear-Host
    Write-Host "=== RDS License Audit Toolkit ===" -ForegroundColor Cyan
    Write-Host "Current License Server: $global:licenseServer"
    Write-Host "1. Set License Server"
    Write-Host "2. Check License Server Configuration"
    Write-Host "3. List Available Licenses"
    Write-Host "4. Analyze License Usage"
    Write-Host "5. Check RDS Server Configuration"
    Write-Host "6. Verify CAL Compliance"
    Write-Host "7. Review License Policies"
    Write-Host "8. Check License Server Health"
    Write-Host "9. Generate Comprehensive HTML Report"
    Write-Host "10. Exit"
}

function Set-LicenseServer {
    $server = Read-Host "Enter the RDS License Server name (or press Enter for localhost)"
    if ([string]::IsNullOrWhiteSpace($server)) {
        $global:licenseServer = $env:COMPUTERNAME
    } else {
        $global:licenseServer = $server
    }
    Write-Host "License server set to: $global:licenseServer" -ForegroundColor Green
}

function Check-LicenseServerConfiguration {
    Write-Host "`nChecking License Server Configuration..." -ForegroundColor Yellow
    try {
        $config = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            $serverInfo = Get-RDLicenseConfiguration
            $serverStatus = Get-RDLicenseServerStatus
            return @{
                ServerInfo = $serverInfo
                ServerStatus = $serverStatus
            }
        }
        
        $result = [PSCustomObject]@{
            Mode = $config.ServerInfo.Mode
            LicensingType = $config.ServerInfo.LicensingType
            IsActivated = $config.ServerStatus.IsActivated
            LastIssuedLicenseDate = $config.ServerStatus.LastIssuedLicenseDate
            GracePeriodDays = $config.ServerStatus.GracePeriodDays
        }
        
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error checking license server configuration: $_" -ForegroundColor Red
        return $null
    }
}

function List-AvailableLicenses {
    Write-Host "`nListing Available Licenses..." -ForegroundColor Yellow
    try {
        $licenses = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            Get-RDLicense
        }
        
        $licenses | Format-Table -AutoSize
        return $licenses
    }
    catch {
        Write-Host "Error listing available licenses: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-LicenseUsage {
    Write-Host "`nAnalyzing License Usage..." -ForegroundColor Yellow
    try {
        $usage = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            Get-RDLicenseUsage
        }
        
        $usage | Format-Table -AutoSize
        return $usage
    }
    catch {
        Write-Host "Error analyzing license usage: $_" -ForegroundColor Red
        return $null
    }
}

function Check-RDSServerConfiguration {
    Write-Host "`nChecking RDS Server Configuration..." -ForegroundColor Yellow
    try {
        $config = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            $deployment = Get-RDDeploymentGatewayConfiguration
            $collection = Get-RDSessionCollection
            return @{
                Deployment = $deployment
                Collection = $collection
            }
        }
        
        $result = [PSCustomObject]@{
            GatewayMode = $config.Deployment.GatewayMode
            CollectionName = $config.Collection.CollectionName
            CollectionDescription = $config.Collection.CollectionDescription
        }
        
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error checking RDS server configuration: $_" -ForegroundColor Red
        return $null
    }
}

function Verify-CALCompliance {
    Write-Host "`nVerifying CAL Compliance..." -ForegroundColor Yellow
    try {
        $compliance = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            $licenses = Get-RDLicense
            $usage = Get-RDLicenseUsage
            
            $totalLicenses = ($licenses | Measure-Object -Property TotalLicenses -Sum).Sum
            $usedLicenses = ($usage | Measure-Object -Property IssuedLicenses -Sum).Sum
            
            return @{
                TotalLicenses = $totalLicenses
                UsedLicenses = $usedLicenses
                IsCompliant = $totalLicenses -ge $usedLicenses
            }
        }
        
        $result = [PSCustomObject]@{
            TotalLicenses = $compliance.TotalLicenses
            UsedLicenses = $compliance.UsedLicenses
            IsCompliant = $compliance.IsCompliant
            ComplianceStatus = if ($compliance.IsCompliant) { "Compliant" } else { "Non-Compliant" }
        }
        
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error verifying CAL compliance: $_" -ForegroundColor Red
        return $null
    }
}

function Review-LicensePolicies {
    Write-Host "`nReviewing License Policies..." -ForegroundColor Yellow
    try {
        $policies = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            Get-RDLicenseConfiguration
        }
        
        $result = [PSCustomObject]@{
            Mode = $policies.Mode
            LicensingType = $policies.LicensingType
            PolicyExpirationDays = $policies.PolicyExpirationDays
            PolicyOverrideAllowed = $policies.PolicyOverrideAllowed
        }
        
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error reviewing license policies: $_" -ForegroundColor Red
        return $null
    }
}

function Check-LicenseServerHealth {
    Write-Host "`nChecking License Server Health..." -ForegroundColor Yellow
    try {
        $health = Invoke-Command -ComputerName $global:licenseServer -ScriptBlock {
            Import-Module RemoteDesktopServices
            $status = Get-RDLicenseServerStatus
            $service = Get-Service -Name TermServLicensing
            
            return @{
                Status = $status
                ServiceStatus = $service.Status
            }
        }
        
        $result = [PSCustomObject]@{
            IsActivated = $health.Status.IsActivated
            LastIssuedLicenseDate = $health.Status.LastIssuedLicenseDate
            GracePeriodDays = $health.Status.GracePeriodDays
            ServiceStatus = $health.ServiceStatus
        }
        
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error checking license server health: $_" -ForegroundColor Red
        return $null
    }
}

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>RDS License Audit 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; }
        .warning { color: orange; }
        .critical { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
    <h1>RDS License Audit Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>License Server: $global:licenseServer</p>

    <h2>License Server Configuration</h2>
    $($AllResults.ServerConfig | ConvertTo-Html -Fragment)

    <h2>Available Licenses</h2>
    $($AllResults.AvailableLicenses | ConvertTo-Html -Fragment)

    <h2>License Usage</h2>
    $($AllResults.LicenseUsage | ConvertTo-Html -Fragment)

    <h2>RDS Server Configuration</h2>
    $($AllResults.RDSConfig | ConvertTo-Html -Fragment)

    <h2>CAL Compliance</h2>
    $($AllResults.CALCompliance | ConvertTo-Html -Fragment)

    <h2>License Policies</h2>
    $($AllResults.LicensePolicies | ConvertTo-Html -Fragment)

    <h2>License Server Health</h2>
    $($AllResults.ServerHealth | 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-10)"

    switch ($choice) {
        "1" { Set-LicenseServer }
        "2" { $allResults.ServerConfig = Check-LicenseServerConfiguration }
        "3" { $allResults.AvailableLicenses = List-AvailableLicenses }
        "4" { $allResults.LicenseUsage = Analyze-LicenseUsage }
        "5" { $allResults.RDSConfig = Check-RDSServerConfiguration }
        "6" { $allResults.CALCompliance = Verify-CALCompliance }
        "7" { $allResults.LicensePolicies = Review-LicensePolicies }
        "8" { $allResults.ServerHealth = Check-LicenseServerHealth }
        "9" { Generate-HTMLReport -AllResults $allResults }
        "10" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This RDS License Audit Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of RDS licensing:
    • License Server Configuration Check
    • Available Licenses Listing
    • License Usage Analysis
    • RDS Server Configuration Check
    • CAL Compliance Verification
    • License Policies Review
    • License Server Health Check
  3. Option to set a target license server (local or remote)
  4. HTML report generation for easy sharing and viewing of results

Key features:

  • Comprehensive RDS license server configuration analysis
  • Detailed listing of available licenses and their types
  • Analysis of current license usage
  • Verification of Client Access License (CAL) compliance
  • Review of RDS deployment and collection configurations
  • Examination of license policies and server health

This tool is particularly useful for:

  • RDS administrators managing license servers
  • IT professionals auditing RDS environments
  • System administrators troubleshooting RDS licensing issues
  • Anyone needing to quickly gather comprehensive information about RDS licensing configuration and usage

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the Remote Desktop Services PowerShell module installed
  3. Have the necessary permissions to query RDS license information (local admin rights on the license server or appropriate delegated permissions)
  4. Review the generated HTML report for a comprehensive overview of the RDS licensing status and configuration

This script provides a thorough analysis of RDS licensing, helping to identify potential issues, compliance concerns, or areas that need attention. It’s designed to give administrators a quick but comprehensive view of their RDS licensing health and configuration.

Workgroup Computer Audit Toolkit

<#
.SYNOPSIS
Workgroup Computer Audit Toolkit

.DESCRIPTION
This script performs a comprehensive audit of a Windows computer that is not part of a domain.
It checks various system settings, security configurations, and local information.

.NOTES
File Name      : WorkgroupComputerAuditToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights on the local machine
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\WorkgroupComputerAuditToolkit.ps1
#>

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

function Show-Menu {
    Clear-Host
    Write-Host "=== Workgroup Computer Audit Toolkit ===" -ForegroundColor Cyan
    Write-Host "1. System Information"
    Write-Host "2. Local User Accounts"
    Write-Host "3. Installed Software"
    Write-Host "4. Windows Update Status"
    Write-Host "5. Security Settings"
    Write-Host "6. Network Configuration"
    Write-Host "7. Shared Folders"
    Write-Host "8. Scheduled Tasks"
    Write-Host "9. Services Analysis"
    Write-Host "10. Generate Comprehensive HTML Report"
    Write-Host "11. Exit"
}

function Get-SystemInformation {
    Write-Host "`nGathering System Information..." -ForegroundColor Yellow
    $os = Get-WmiObject Win32_OperatingSystem
    $cs = Get-WmiObject Win32_ComputerSystem
    $bios = Get-WmiObject Win32_BIOS

    $result = [PSCustomObject]@{
        ComputerName = $env:COMPUTERNAME
        OSName = $os.Caption
        OSVersion = $os.Version
        OSArchitecture = $os.OSArchitecture
        Manufacturer = $cs.Manufacturer
        Model = $cs.Model
        BIOSVersion = $bios.SMBIOSBIOSVersion
        LastBootUpTime = $os.ConvertToDateTime($os.LastBootUpTime)
        InstallDate = $os.ConvertToDateTime($os.InstallDate)
        WorkgroupName = $cs.Workgroup
    }

    $result | Format-List
    return $result
}

function Get-LocalUserAccounts {
    Write-Host "`nGathering Local User Account Information..." -ForegroundColor Yellow
    $users = Get-WmiObject Win32_UserAccount -Filter "LocalAccount=True"
    $results = @()

    foreach ($user in $users) {
        $results += [PSCustomObject]@{
            Username = $user.Name
            FullName = $user.FullName
            Disabled = $user.Disabled
            PasswordRequired = $user.PasswordRequired
            PasswordChangeable = $user.PasswordChangeable
            PasswordExpires = $user.PasswordExpires
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-InstalledSoftware {
    Write-Host "`nGathering Installed Software Information..." -ForegroundColor Yellow
    $software = Get-WmiObject Win32_Product | Select-Object Name, Version, Vendor, InstallDate
    $software | Format-Table -AutoSize
    return $software
}

function Get-WindowsUpdateStatus {
    Write-Host "`nChecking Windows Update Status..." -ForegroundColor Yellow
    $updateSession = New-Object -ComObject Microsoft.Update.Session
    $updateSearcher = $updateSession.CreateUpdateSearcher()
    $pendingUpdates = $updateSearcher.Search("IsInstalled=0")

    $result = [PSCustomObject]@{
        PendingUpdatesCount = $pendingUpdates.Updates.Count
        LastUpdateDate = (Get-HotFix | Sort-Object -Property InstalledOn -Descending | Select-Object -First 1).InstalledOn
    }

    $result | Format-List
    return $result
}

function Get-SecuritySettings {
    Write-Host "`nGathering Security Settings..." -ForegroundColor Yellow
    $firewallStatus = Get-NetFirewallProfile | Select-Object Name, Enabled
    $avProduct = Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct
    $uac = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA"

    $result = [PSCustomObject]@{
        FirewallStatus = $firewallStatus
        AntiVirusProduct = $avProduct.displayName
        UACEnabled = $uac.EnableLUA -eq 1
    }

    $result | Format-List
    return $result
}

function Get-NetworkConfiguration {
    Write-Host "`nGathering Network Configuration..." -ForegroundColor Yellow
    $adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true }
    $results = @()

    foreach ($adapter in $adapters) {
        $results += [PSCustomObject]@{
            AdapterName = $adapter.Description
            IPAddress = $adapter.IPAddress -join ", "
            SubnetMask = $adapter.IPSubnet -join ", "
            DefaultGateway = $adapter.DefaultIPGateway -join ", "
            DNSServers = $adapter.DNSServerSearchOrder -join ", "
            MACAddress = $adapter.MACAddress
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-SharedFolders {
    Write-Host "`nGathering Shared Folder Information..." -ForegroundColor Yellow
    $shares = Get-WmiObject Win32_Share
    $results = @()

    foreach ($share in $shares) {
        $results += [PSCustomObject]@{
            Name = $share.Name
            Path = $share.Path
            Description = $share.Description
            Type = switch ($share.Type) {
                0 {"Disk Drive"}
                1 {"Print Queue"}
                2 {"Device"}
                3 {"IPC"}
                2147483648 {"Disk Drive Admin"}
                2147483649 {"Print Queue Admin"}
                2147483650 {"Device Admin"}
                2147483651 {"IPC Admin"}
            }
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-ScheduledTasks {
    Write-Host "`nGathering Scheduled Task Information..." -ForegroundColor Yellow
    $tasks = Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"}
    $results = @()

    foreach ($task in $tasks) {
        $results += [PSCustomObject]@{
            TaskName = $task.TaskName
            State = $task.State
            LastRunTime = $task.LastRunTime
            NextRunTime = $task.NextRunTime
            Author = $task.Author
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-ServicesAnalysis {
    Write-Host "`nAnalyzing Services..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service
    $results = @()

    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Name = $service.Name
            DisplayName = $service.DisplayName
            StartMode = $service.StartMode
            State = $service.State
            StartName = $service.StartName
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

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>Workgroup Computer Audit 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; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>Workgroup Computer Audit Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>System Information</h2>
    $($AllResults.SystemInfo | ConvertTo-Html -Fragment)

    <h2>Local User Accounts</h2>
    $($AllResults.LocalUsers | ConvertTo-Html -Fragment)

    <h2>Installed Software</h2>
    $($AllResults.InstalledSoftware | ConvertTo-Html -Fragment)

    <h2>Windows Update Status</h2>
    $($AllResults.WindowsUpdateStatus | ConvertTo-Html -Fragment)

    <h2>Security Settings</h2>
    $($AllResults.SecuritySettings | ConvertTo-Html -Fragment)

    <h2>Network Configuration</h2>
    $($AllResults.NetworkConfig | ConvertTo-Html -Fragment)

    <h2>Shared Folders</h2>
    $($AllResults.SharedFolders | ConvertTo-Html -Fragment)

    <h2>Scheduled Tasks</h2>
    $($AllResults.ScheduledTasks | ConvertTo-Html -Fragment)

    <h2>Services Analysis</h2>
    $($AllResults.ServicesAnalysis | 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-11)"

    switch ($choice) {
        "1" { $allResults.SystemInfo = Get-SystemInformation }
        "2" { $allResults.LocalUsers = Get-LocalUserAccounts }
        "3" { $allResults.InstalledSoftware = Get-InstalledSoftware }
        "4" { $allResults.WindowsUpdateStatus = Get-WindowsUpdateStatus }
        "5" { $allResults.SecuritySettings = Get-SecuritySettings }
        "6" { $allResults.NetworkConfig = Get-NetworkConfiguration }
        "7" { $allResults.SharedFolders = Get-SharedFolders }
        "8" { $allResults.ScheduledTasks = Get-ScheduledTasks }
        "9" { $allResults.ServicesAnalysis = Get-ServicesAnalysis }
        "10" { Generate-HTMLReport -AllResults $allResults }
        "11" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Workgroup Computer Audit Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to gather various aspects of the local Windows computer:
    • System Information
    • Local User Accounts
    • Installed Software
    • Windows Update Status
    • Security Settings
    • Network Configuration
    • Shared Folders
    • Scheduled Tasks
    • Services Analysis
  3. HTML report generation for easy sharing and viewing of results.

Key features:

  • Comprehensive system information gathering
  • Local user account analysis
  • Software inventory
  • Windows Update status check
  • Basic security settings review (firewall, antivirus, UAC)
  • Network configuration details
  • Shared folder enumeration
  • Active scheduled tasks listing
  • Services analysis

This tool is particularly useful for:

  • IT administrators performing audits on standalone or workgroup computers
  • Security professionals assessing the configuration of non-domain Windows machines
  • Help desk personnel gathering system information for troubleshooting
  • Anyone needing to quickly collect comprehensive information about a Windows computer not joined to a domain

To use this script effectively:

  1. Run PowerShell as an administrator on the Windows computer you want to audit
  2. Ensure you have the necessary permissions to query system information
  3. Review the generated HTML report for a comprehensive overview of the computer’s configuration

This script provides a thorough audit of a workgroup Windows computer, helping to identify potential issues, misconfigurations, or security concerns. It’s designed to be run locally on the machine being audited, making it suitable for situations where centralized management tools are not available.

LDAP and LDAPS Check Toolkit

<#
.SYNOPSIS
LDAP and LDAPS Check Toolkit

.DESCRIPTION
This script provides comprehensive checks and tests for LDAP and LDAPS configurations,
including connectivity, security, and certificate validation.

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

.EXAMPLE
.\LDAPCheckToolkit.ps1
#>

# Import required modules
Import-Module ActiveDirectory

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\LDAP_Check_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
$global:ldapServer = $env:COMPUTERNAME  # Default to local machine
$global:ldapPort = 389  # Default LDAP port
$global:ldapsPort = 636  # Default LDAPS port

function Show-Menu {
    Clear-Host
    Write-Host "=== LDAP and LDAPS Check Toolkit ===" -ForegroundColor Cyan
    Write-Host "Current LDAP Server: $global:ldapServer"
    Write-Host "1. Set LDAP Server"
    Write-Host "2. Test LDAP Connectivity"
    Write-Host "3. Test LDAPS Connectivity"
    Write-Host "4. Check LDAP Binding"
    Write-Host "5. Verify LDAP SSL Certificate"
    Write-Host "6. Check LDAP Server Capabilities"
    Write-Host "7. Test LDAP Query"
    Write-Host "8. Check LDAP Security Settings"
    Write-Host "9. Analyze LDAP Traffic"
    Write-Host "10. Generate Comprehensive HTML Report"
    Write-Host "11. Exit"
}

function Set-LDAPServer {
    $server = Read-Host "Enter the LDAP server name (or press Enter for localhost)"
    if ([string]::IsNullOrWhiteSpace($server)) {
        $global:ldapServer = $env:COMPUTERNAME
    } else {
        $global:ldapServer = $server
    }
    Write-Host "LDAP server set to: $global:ldapServer" -ForegroundColor Green
}

function Test-LDAPConnectivity {
    Write-Host "`nTesting LDAP Connectivity..." -ForegroundColor Yellow
    try {
        $result = Test-NetConnection -ComputerName $global:ldapServer -Port $global:ldapPort
        if ($result.TcpTestSucceeded) {
            Write-Host "LDAP connectivity test successful." -ForegroundColor Green
        } else {
            Write-Host "LDAP connectivity test failed." -ForegroundColor Red
        }
        return $result
    }
    catch {
        Write-Host "Error testing LDAP connectivity: $_" -ForegroundColor Red
        return $null
    }
}

function Test-LDAPSConnectivity {
    Write-Host "`nTesting LDAPS Connectivity..." -ForegroundColor Yellow
    try {
        $result = Test-NetConnection -ComputerName $global:ldapServer -Port $global:ldapsPort
        if ($result.TcpTestSucceeded) {
            Write-Host "LDAPS connectivity test successful." -ForegroundColor Green
        } else {
            Write-Host "LDAPS connectivity test failed." -ForegroundColor Red
        }
        return $result
    }
    catch {
        Write-Host "Error testing LDAPS connectivity: $_" -ForegroundColor Red
        return $null
    }
}

function Check-LDAPBinding {
    Write-Host "`nChecking LDAP Binding..." -ForegroundColor Yellow
    try {
        $domainDN = (Get-ADDomain).DistinguishedName
        $ldapPath = "LDAP://$global:ldapServer/$domainDN"
        $ldapConnection = New-Object System.DirectoryServices.DirectoryEntry($ldapPath)
        
        if ($ldapConnection.Name -ne $null) {
            Write-Host "LDAP binding successful." -ForegroundColor Green
            $result = @{
                Success = $true
                Path = $ldapPath
                Name = $ldapConnection.Name
            }
        } else {
            Write-Host "LDAP binding failed." -ForegroundColor Red
            $result = @{
                Success = $false
                Path = $ldapPath
                Error = "Unable to bind to LDAP server"
            }
        }
        return $result
    }
    catch {
        Write-Host "Error checking LDAP binding: $_" -ForegroundColor Red
        return @{
            Success = $false
            Path = $ldapPath
            Error = $_.Exception.Message
        }
    }
}

function Verify-LDAPSSLCertificate {
    Write-Host "`nVerifying LDAP SSL Certificate..." -ForegroundColor Yellow
    try {
        $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
        $cert.Import("LDAP://$global:ldapServer`:$global:ldapsPort")
        
        $result = @{
            Subject = $cert.Subject
            Issuer = $cert.Issuer
            ValidFrom = $cert.NotBefore
            ValidTo = $cert.NotAfter
            Thumbprint = $cert.Thumbprint
        }
        
        if ((Get-Date) -gt $cert.NotAfter) {
            Write-Host "SSL Certificate has expired." -ForegroundColor Red
        } else {
            Write-Host "SSL Certificate is valid." -ForegroundColor Green
        }
        
        return $result
    }
    catch {
        Write-Host "Error verifying LDAP SSL Certificate: $_" -ForegroundColor Red
        return $null
    }
}

function Check-LDAPServerCapabilities {
    Write-Host "`nChecking LDAP Server Capabilities..." -ForegroundColor Yellow
    try {
        $rootDSE = [ADSI]"LDAP://$global:ldapServer/RootDSE"
        $capabilities = $rootDSE.supportedCapabilities
        $ldapVersion = $rootDSE.supportedLDAPVersion
        $controls = $rootDSE.supportedControl
        
        $result = @{
            SupportedCapabilities = $capabilities
            SupportedLDAPVersion = $ldapVersion
            SupportedControls = $controls
        }
        
        Write-Host "LDAP Server Capabilities retrieved successfully." -ForegroundColor Green
        return $result
    }
    catch {
        Write-Host "Error checking LDAP Server Capabilities: $_" -ForegroundColor Red
        return $null
    }
}

function Test-LDAPQuery {
    Write-Host "`nTesting LDAP Query..." -ForegroundColor Yellow
    try {
        $domainDN = (Get-ADDomain).DistinguishedName
        $searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"LDAP://$global:ldapServer/$domainDN")
        $searcher.Filter = "(objectClass=user)"
        $searcher.SizeLimit = 5
        $results = $searcher.FindAll()
        
        $queryResults = @()
        foreach ($result in $results) {
            $queryResults += [PSCustomObject]@{
                Name = $result.Properties["name"][0]
                DistinguishedName = $result.Properties["distinguishedname"][0]
            }
        }
        
        Write-Host "LDAP Query test successful." -ForegroundColor Green
        return $queryResults
    }
    catch {
        Write-Host "Error testing LDAP Query: $_" -ForegroundColor Red
        return $null
    }
}

function Check-LDAPSecuritySettings {
    Write-Host "`nChecking LDAP Security Settings..." -ForegroundColor Yellow
    try {
        $ntdsSettings = Get-ADObject -Identity "CN=NTDS Settings,CN=$global:ldapServer,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,$((Get-ADDomain).DistinguishedName)" -Properties *
        
        $result = @{
            LDAPServerSigningRequired = $ntdsSettings.LDAPServerIntegrity -eq 2
            LDAPSEnabled = $ntdsSettings.SSLPort -ne $null
            NTLMAuthEnabled = $ntdsSettings.SupportedSASLMechanisms -contains "GSSAPI"
            KerberosAuthEnabled = $ntdsSettings.SupportedSASLMechanisms -contains "GSS-SPNEGO"
        }
        
        Write-Host "LDAP Security Settings retrieved successfully." -ForegroundColor Green
        return $result
    }
    catch {
        Write-Host "Error checking LDAP Security Settings: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-LDAPTraffic {
    Write-Host "`nAnalyzing LDAP Traffic..." -ForegroundColor Yellow
    Write-Host "This function would typically use network monitoring tools to analyze LDAP traffic."
    Write-Host "For security and complexity reasons, actual traffic analysis is not implemented in this script."
    Write-Host "Consider using tools like Wireshark or Microsoft Network Monitor for detailed LDAP traffic analysis."
    
    # Placeholder for traffic analysis results
    $result = @{
        TotalConnections = "N/A"
        AverageResponseTime = "N/A"
        ErrorRate = "N/A"
    }
    
    return $result
}

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>LDAP and LDAPS Check 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; }
        .success { color: green; }
        .warning { color: orange; }
        .error { color: red; }
    </style>
</head>
<body>
    <h1>LDAP and LDAPS Check Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>LDAP Server: $global:ldapServer</p>

    <h2>LDAP Connectivity</h2>
    $($AllResults.LDAPConnectivity | ConvertTo-Html -Fragment)

    <h2>LDAPS Connectivity</h2>
    $($AllResults.LDAPSConnectivity | ConvertTo-Html -Fragment)

    <h2>LDAP Binding</h2>
    $($AllResults.LDAPBinding | ConvertTo-Html -Fragment)

    <h2>LDAP SSL Certificate</h2>
    $($AllResults.LDAPSSLCertificate | ConvertTo-Html -Fragment)

    <h2>LDAP Server Capabilities</h2>
    $($AllResults.ServerCapabilities | ConvertTo-Html -Fragment)

    <h2>LDAP Query Test</h2>
    $($AllResults.LDAPQuery | ConvertTo-Html -Fragment)

    <h2>LDAP Security Settings</h2>
    $($AllResults.SecuritySettings | ConvertTo-Html -Fragment)

    <h2>LDAP Traffic Analysis</h2>
    $($AllResults.TrafficAnalysis | 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-11)"

    switch ($choice) {
        "1" { Set-LDAPServer }
        "2" { $allResults.LDAPConnectivity = Test-LDAPConnectivity }
        "3" { $allResults.LDAPSConnectivity = Test-LDAPSConnectivity }
        "4" { $allResults.LDAPBinding = Check-LDAPBinding }
        "5" { $allResults.LDAPSSLCertificate = Verify-LDAPSSLCertificate }
        "6" { $allResults.ServerCapabilities = Check-LDAPServerCapabilities }
        "7" { $allResults.LDAPQuery = Test-LDAPQuery }
        "8" { $allResults.SecuritySettings = Check-LDAPSecuritySettings }
        "9" { $allResults.TrafficAnalysis = Analyze-LDAPTraffic }
        "10" { Generate-HTMLReport -AllResults $allResults }
        "11" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This LDAP and LDAPS Check Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze and test various aspects of LDAP and LDAPS:
    • LDAP and LDAPS Connectivity Tests
    • LDAP Binding Check
    • LDAP SSL Certificate Verification
    • LDAP Server Capabilities Check
    • LDAP Query Test
    • LDAP Security Settings Check
    • LDAP Traffic Analysis (placeholder)
  3. Option to set a target LDAP server (local or remote)
  4. HTML report generation for easy sharing and viewing of results

Key features:

  • Comprehensive LDAP and LDAPS connectivity testing
  • Detailed SSL certificate verification for LDAPS
  • Analysis of LDAP server capabilities and supported features
  • Basic LDAP query testing
  • Review of LDAP security settings
  • Placeholder for LDAP traffic analysis (which would typically require additional tools)

This tool is particularly useful for:

  • System administrators managing LDAP-enabled environments
  • Security professionals auditing LDAP configurations
  • IT professionals troubleshooting LDAP-related issues
  • Anyone needing to quickly gather comprehensive information about LDAP and LDAPS configurations

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the Active Directory PowerShell module installed
  3. Have the necessary permissions to query LDAP server information
  4. Review the generated HTML report for a comprehensive overview of the LDAP server’s configuration and status

Note: The LDAP traffic analysis function is a placeholder and would typically require additional network monitoring tools to implement fully. For actual traffic analysis, consider using specialized tools like Wireshark or Microsoft Network Monitor.

This script provides a thorough analysis of LDAP and LDAPS configurations, helping to identify potential issues, misconfigurations, or security concerns. It’s designed to give administrators a quick but comprehensive view of their LDAP server’s health and configuration.

DHCP Toolkit

<#
.SYNOPSIS
DHCP Toolkit

.DESCRIPTION
This script provides comprehensive analysis and management options for DHCP servers in a Windows environment.

.NOTES
File Name      : DHCPToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, DHCP Server module, and appropriate admin rights
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\DHCPToolkit.ps1
#>

# Import required module
Import-Module DHCPServer

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\DHCP_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
$global:dhcpServer = $env:COMPUTERNAME  # Default to local machine

function Show-Menu {
    Clear-Host
    Write-Host "=== DHCP Toolkit ===" -ForegroundColor Cyan
    Write-Host "Current DHCP Server: $global:dhcpServer"
    Write-Host "1. Set DHCP Server"
    Write-Host "2. Get DHCP Server Information"
    Write-Host "3. List DHCP Scopes"
    Write-Host "4. Analyze Scope Utilization"
    Write-Host "5. Check DHCP Options"
    Write-Host "6. List DHCP Reservations"
    Write-Host "7. Check DHCP Failover Configuration"
    Write-Host "8. Analyze DHCP Lease History"
    Write-Host "9. Check DHCP Server Statistics"
    Write-Host "10. Generate Comprehensive HTML Report"
    Write-Host "11. Exit"
}

function Set-DHCPServer {
    $server = Read-Host "Enter the DHCP server name (or press Enter for localhost)"
    if ([string]::IsNullOrWhiteSpace($server)) {
        $global:dhcpServer = $env:COMPUTERNAME
    } else {
        $global:dhcpServer = $server
    }
    Write-Host "DHCP server set to: $global:dhcpServer" -ForegroundColor Green
}

function Get-DHCPServerInformation {
    Write-Host "`nGathering DHCP Server Information..." -ForegroundColor Yellow
    try {
        $serverInfo = Get-DhcpServerSetting -ComputerName $global:dhcpServer
        $result = [PSCustomObject]@{
            ServerName = $global:dhcpServer
            ConflictDetectionAttempts = $serverInfo.ConflictDetectionAttempts
            DynamicBootp = $serverInfo.DynamicBootp
            IsAuthorized = $serverInfo.IsAuthorized
            NapEnabled = $serverInfo.NapEnabled
            RestoreStatus = $serverInfo.RestoreStatus
        }
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error getting DHCP server information: $_" -ForegroundColor Red
        return $null
    }
}

function Get-DHCPScopes {
    Write-Host "`nListing DHCP Scopes..." -ForegroundColor Yellow
    try {
        $scopes = Get-DhcpServerv4Scope -ComputerName $global:dhcpServer
        $scopes | Format-Table -AutoSize
        return $scopes
    }
    catch {
        Write-Host "Error getting DHCP scopes: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-ScopeUtilization {
    Write-Host "`nAnalyzing Scope Utilization..." -ForegroundColor Yellow
    try {
        $scopes = Get-DhcpServerv4Scope -ComputerName $global:dhcpServer
        $results = @()
        foreach ($scope in $scopes) {
            $stats = Get-DhcpServerv4ScopeStatistics -ComputerName $global:dhcpServer -ScopeId $scope.ScopeId
            $results += [PSCustomObject]@{
                ScopeName = $scope.Name
                ScopeId = $scope.ScopeId
                TotalAddresses = $stats.TotalAddresses
                InUse = $stats.AddressesInUse
                Available = $stats.AddressesAvailable
                UtilizationPercentage = [math]::Round(($stats.AddressesInUse / $stats.TotalAddresses) * 100, 2)
            }
        }
        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error analyzing scope utilization: $_" -ForegroundColor Red
        return $null
    }
}

function Check-DHCPOptions {
    Write-Host "`nChecking DHCP Options..." -ForegroundColor Yellow
    try {
        $serverOptions = Get-DhcpServerv4OptionValue -ComputerName $global:dhcpServer
        $scopeOptions = Get-DhcpServerv4Scope -ComputerName $global:dhcpServer | ForEach-Object {
            Get-DhcpServerv4OptionValue -ComputerName $global:dhcpServer -ScopeId $_.ScopeId
        }
        
        $results = @{
            ServerOptions = $serverOptions
            ScopeOptions = $scopeOptions
        }
        
        $serverOptions | Format-Table -AutoSize
        Write-Host "Scope-specific options are available in the returned object." -ForegroundColor Yellow
        return $results
    }
    catch {
        Write-Host "Error checking DHCP options: $_" -ForegroundColor Red
        return $null
    }
}

function List-DHCPReservations {
    Write-Host "`nListing DHCP Reservations..." -ForegroundColor Yellow
    try {
        $scopes = Get-DhcpServerv4Scope -ComputerName $global:dhcpServer
        $results = @()
        foreach ($scope in $scopes) {
            $reservations = Get-DhcpServerv4Reservation -ComputerName $global:dhcpServer -ScopeId $scope.ScopeId
            foreach ($reservation in $reservations) {
                $results += [PSCustomObject]@{
                    ScopeId = $scope.ScopeId
                    IPAddress = $reservation.IPAddress
                    ClientId = $reservation.ClientId
                    Name = $reservation.Name
                }
            }
        }
        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error listing DHCP reservations: $_" -ForegroundColor Red
        return $null
    }
}

function Check-DHCPFailover {
    Write-Host "`nChecking DHCP Failover Configuration..." -ForegroundColor Yellow
    try {
        $failoverRelationships = Get-DhcpServerv4Failover -ComputerName $global:dhcpServer
        if ($failoverRelationships) {
            $failoverRelationships | Format-Table -AutoSize
        } else {
            Write-Host "No failover relationships configured." -ForegroundColor Yellow
        }
        return $failoverRelationships
    }
    catch {
        Write-Host "Error checking DHCP failover configuration: $_" -ForegroundColor Red
        return $null
    }
}

function Analyze-DHCPLeaseHistory {
    Write-Host "`nAnalyzing DHCP Lease History..." -ForegroundColor Yellow
    try {
        $startDate = (Get-Date).AddDays(-7)
        $leaseHistory = Get-DhcpServerv4ScopeStatistics -ComputerName $global:dhcpServer | ForEach-Object {
            Get-DhcpServerv4LeaseHistory -ComputerName $global:dhcpServer -ScopeId $_.ScopeId -StartDate $startDate
        }
        
        $results = $leaseHistory | Group-Object ScopeId | ForEach-Object {
            [PSCustomObject]@{
                ScopeId = $_.Name
                LeaseCount = $_.Count
                UniqueClients = ($_.Group | Select-Object -ExpandProperty ClientId -Unique).Count
            }
        }
        
        $results | Format-Table -AutoSize
        return $results
    }
    catch {
        Write-Host "Error analyzing DHCP lease history: $_" -ForegroundColor Red
        return $null
    }
}

function Check-DHCPServerStatistics {
    Write-Host "`nChecking DHCP Server Statistics..." -ForegroundColor Yellow
    try {
        $stats = Get-DhcpServerStatistics -ComputerName $global:dhcpServer
        $result = [PSCustomObject]@{
            TotalScopes = $stats.TotalScopes
            TotalAddresses = $stats.TotalAddresses
            AddressesInUse = $stats.AddressesInUse
            AddressesAvailable = $stats.AddressesAvailable
            PercentageInUse = [math]::Round(($stats.AddressesInUse / $stats.TotalAddresses) * 100, 2)
            Discovers = $stats.Discovers
            Offers = $stats.Offers
            Requests = $stats.Requests
            Acks = $stats.Acks
            Naks = $stats.Naks
            Declines = $stats.Declines
            Releases = $stats.Releases
        }
        $result | Format-List
        return $result
    }
    catch {
        Write-Host "Error checking DHCP server statistics: $_" -ForegroundColor Red
        return $null
    }
}

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>DHCP Server 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; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>DHCP Server Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>DHCP Server: $global:dhcpServer</p>

    <h2>DHCP Server Information</h2>
    $($AllResults.ServerInfo | ConvertTo-Html -Fragment)

    <h2>DHCP Scopes</h2>
    $($AllResults.Scopes | ConvertTo-Html -Fragment)

    <h2>Scope Utilization</h2>
    $($AllResults.ScopeUtilization | ConvertTo-Html -Fragment)

    <h2>DHCP Options</h2>
    <h3>Server Options</h3>
    $($AllResults.DHCPOptions.ServerOptions | ConvertTo-Html -Fragment)

    <h2>DHCP Reservations</h2>
    $($AllResults.Reservations | ConvertTo-Html -Fragment)

    <h2>DHCP Failover Configuration</h2>
    $($AllResults.FailoverConfig | ConvertTo-Html -Fragment)

    <h2>DHCP Lease History (Last 7 Days)</h2>
    $($AllResults.LeaseHistory | ConvertTo-Html -Fragment)

    <h2>DHCP Server Statistics</h2>
    $($AllResults.ServerStats | 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-11)"

    switch ($choice) {
        "1" { Set-DHCPServer }
        "2" { $allResults.ServerInfo = Get-DHCPServerInformation }
        "3" { $allResults.Scopes = Get-DHCPScopes }
        "4" { $allResults.ScopeUtilization = Analyze-ScopeUtilization }
        "5" { $allResults.DHCPOptions = Check-DHCPOptions }
        "6" { $allResults.Reservations = List-DHCPReservations }
        "7" { $allResults.FailoverConfig = Check-DHCPFailover }
        "8" { $allResults.LeaseHistory = Analyze-DHCPLeaseHistory }
        "9" { $allResults.ServerStats = Check-DHCPServerStatistics }
        "10" { Generate-HTMLReport -AllResults $allResults }
        "11" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This DHCP Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze and manage various aspects of DHCP servers:
    • DHCP Server Information
    • DHCP Scopes Listing
    • Scope Utilization Analysis
    • DHCP Options Check
    • DHCP Reservations Listing
    • DHCP Failover Configuration Check
    • DHCP Lease History Analysis
    • DHCP Server Statistics Check
  3. Option to set a target DHCP server (local or remote)
  4. HTML report generation for easy sharing and viewing of results

Key features:

  • Comprehensive DHCP server information gathering
  • Detailed analysis of scope utilization
  • Review of DHCP options at server and scope level
  • Listing of DHCP reservations across all scopes
  • Failover configuration check
  • Analysis of recent lease history
  • Overview of DHCP server statistics

This tool is particularly useful for:

  • Network administrators managing DHCP servers
  • IT professionals troubleshooting DHCP-related issues
  • System administrators performing regular DHCP health checks
  • Anyone needing to quickly gather comprehensive information about DHCP server configurations

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the DHCP Server PowerShell module installed (typically available on DHCP servers or management workstations)
  3. Have the necessary permissions to query DHCP server information (local admin rights on the DHCP server or appropriate delegated permissions)
  4. Review the generated HTML report for a comprehensive overview of the DHCP server’s configuration and status

This script provides a thorough analysis of a DHCP server, helping to identify potential issues, misconfigurations, or areas that need attention. It’s designed to give administrators a quick but comprehensive view of their DHCP server’s health and configuration.

Domain Check Toolkit

<#
.SYNOPSIS
Domain Check Toolkit

.DESCRIPTION
This script performs comprehensive checks and information gathering on an Active Directory domain,
providing insights into domain controllers, users, groups, GPOs, and other domain-related configurations.

.NOTES
File Name      : DomainCheckToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, Active Directory module, and appropriate domain admin rights
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\DomainCheckToolkit.ps1
#>

# Import required modules
Import-Module ActiveDirectory

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

function Show-Menu {
    Clear-Host
    Write-Host "=== Domain Check Toolkit ===" -ForegroundColor Cyan
    Write-Host "1. Domain Information"
    Write-Host "2. Domain Controller Health Check"
    Write-Host "3. User Account Analysis"
    Write-Host "4. Group Analysis"
    Write-Host "5. Group Policy Object (GPO) Check"
    Write-Host "6. DNS Health Check"
    Write-Host "7. FSMO Roles Check"
    Write-Host "8. Replication Status"
    Write-Host "9. Trust Relationships"
    Write-Host "10. Generate Comprehensive HTML Report"
    Write-Host "11. Exit"
}

function Get-DomainInformation {
    Write-Host "`nGathering Domain Information..." -ForegroundColor Yellow
    $domainInfo = Get-ADDomain
    $forestInfo = Get-ADForest

    $result = [PSCustomObject]@{
        DomainName = $domainInfo.DNSRoot
        NetBIOSName = $domainInfo.NetBIOSName
        DomainMode = $domainInfo.DomainMode
        ForestName = $forestInfo.Name
        ForestMode = $forestInfo.ForestMode
        DomainControllers = ($domainInfo.ReplicaDirectoryServers -join ", ")
        GlobalCatalogs = ($forestInfo.GlobalCatalogs -join ", ")
    }

    $result | Format-List
    return $result
}

function Get-DomainControllerHealth {
    Write-Host "`nPerforming Domain Controller Health Check..." -ForegroundColor Yellow
    $dcs = Get-ADDomainController -Filter *
    $results = @()

    foreach ($dc in $dcs) {
        $dcdiag = dcdiag /s:$($dc.HostName) /test:services /test:advertising /test:fsmocheck /test:ridmanager
        $results += [PSCustomObject]@{
            Name = $dc.HostName
            Site = $dc.Site
            IPv4Address = $dc.IPv4Address
            OperatingSystem = $dc.OperatingSystem
            IsGlobalCatalog = $dc.IsGlobalCatalog
            ServicesTest = if ($dcdiag -match "passed test Services") { "Passed" } else { "Failed" }
            AdvertisingTest = if ($dcdiag -match "passed test Advertising") { "Passed" } else { "Failed" }
            FSMOCheckTest = if ($dcdiag -match "passed test FsmoCheck") { "Passed" } else { "Failed" }
            RidManagerTest = if ($dcdiag -match "passed test RidManager") { "Passed" } else { "Failed" }
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-UserAccountAnalysis {
    Write-Host "`nPerforming User Account Analysis..." -ForegroundColor Yellow
    $users = Get-ADUser -Filter * -Properties Enabled, PasswordLastSet, LastLogonDate, PasswordNeverExpires
    $results = @{
        TotalUsers = $users.Count
        EnabledUsers = ($users | Where-Object { $_.Enabled -eq $true }).Count
        DisabledUsers = ($users | Where-Object { $_.Enabled -eq $false }).Count
        PasswordNeverExpires = ($users | Where-Object { $_.PasswordNeverExpires -eq $true }).Count
        InactiveUsers = ($users | Where-Object { $_.LastLogonDate -lt (Get-Date).AddDays(-90) }).Count
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-GroupAnalysis {
    Write-Host "`nPerforming Group Analysis..." -ForegroundColor Yellow
    $groups = Get-ADGroup -Filter *
    $results = @{
        TotalGroups = $groups.Count
        SecurityGroups = ($groups | Where-Object { $_.GroupCategory -eq "Security" }).Count
        DistributionGroups = ($groups | Where-Object { $_.GroupCategory -eq "Distribution" }).Count
        GlobalGroups = ($groups | Where-Object { $_.GroupScope -eq "Global" }).Count
        UniversalGroups = ($groups | Where-Object { $_.GroupScope -eq "Universal" }).Count
        DomainLocalGroups = ($groups | Where-Object { $_.GroupScope -eq "DomainLocal" }).Count
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-GPOCheck {
    Write-Host "`nPerforming Group Policy Object Check..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $results = @()

    foreach ($gpo in $gpos) {
        $results += [PSCustomObject]@{
            Name = $gpo.DisplayName
            ID = $gpo.Id
            CreationTime = $gpo.CreationTime
            ModificationTime = $gpo.ModificationTime
            UserVersionNumber = $gpo.UserVersion.DSVersion
            ComputerVersionNumber = $gpo.ComputerVersion.DSVersion
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-DNSHealthCheck {
    Write-Host "`nPerforming DNS Health Check..." -ForegroundColor Yellow
    $dnsServers = Get-ADDomainController -Filter * | Select-Object -ExpandProperty Name
    $results = @()

    foreach ($server in $dnsServers) {
        $dnsTest = Test-DnsServer -ComputerName $server -Context DnsServer
        $results += [PSCustomObject]@{
            Server = $server
            IsResponding = $dnsTest.IsResponding
            TCPPort53Open = ($dnsTest.TcpOpen -contains 53)
            UDPPort53Open = ($dnsTest.UdpOpen -contains 53)
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

function Get-FSMORolesCheck {
    Write-Host "`nChecking FSMO Roles..." -ForegroundColor Yellow
    $domain = Get-ADDomain
    $forest = Get-ADForest

    $result = [PSCustomObject]@{
        PDCEmulator = $domain.PDCEmulator
        RIDMaster = $domain.RIDMaster
        InfrastructureMaster = $domain.InfrastructureMaster
        SchemaMaster = $forest.SchemaMaster
        DomainNamingMaster = $forest.DomainNamingMaster
    }

    $result | Format-List
    return $result
}

function Get-ReplicationStatus {
    Write-Host "`nChecking Replication Status..." -ForegroundColor Yellow
    $results = @()
    $repl = repadmin /showrepl * /csv
    $replData = ConvertFrom-Csv $repl

    foreach ($item in $replData) {
        if ($item."Number of Failures" -ne "0") {
            $results += [PSCustomObject]@{
                SourceDC = $item."Source DC"
                DestinationDC = $item."Destination DC"
                FailureCount = $item."Number of Failures"
                LastFailureTime = $item."Last Failure Time"
                LastSuccessTime = $item."Last Success Time"
            }
        }
    }

    if ($results.Count -eq 0) {
        Write-Host "No replication failures detected." -ForegroundColor Green
    } else {
        $results | Format-Table -AutoSize
    }
    return $results
}

function Get-TrustRelationships {
    Write-Host "`nChecking Trust Relationships..." -ForegroundColor Yellow
    $trusts = Get-ADTrust -Filter *
    $results = @()

    foreach ($trust in $trusts) {
        $results += [PSCustomObject]@{
            Name = $trust.Name
            Direction = $trust.Direction
            TrustType = $trust.TrustType
            ForestTransitive = $trust.ForestTransitive
            IntraForest = $trust.IntraForest
        }
    }

    $results | Format-Table -AutoSize
    return $results
}

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>Domain Check 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; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>Domain Check Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>Domain Information</h2>
    $($AllResults.DomainInfo | ConvertTo-Html -Fragment)

    <h2>Domain Controller Health</h2>
    $($AllResults.DCHealth | ConvertTo-Html -Fragment)

    <h2>User Account Analysis</h2>
    $($AllResults.UserAnalysis | ConvertTo-Html -Fragment)

    <h2>Group Analysis</h2>
    $($AllResults.GroupAnalysis | ConvertTo-Html -Fragment)

    <h2>Group Policy Objects</h2>
    $($AllResults.GPOCheck | ConvertTo-Html -Fragment)

    <h2>DNS Health Check</h2>
    $($AllResults.DNSHealth | ConvertTo-Html -Fragment)

    <h2>FSMO Roles</h2>
    $($AllResults.FSMORoles | ConvertTo-Html -Fragment)

    <h2>Replication Status</h2>
    $($AllResults.ReplicationStatus | ConvertTo-Html -Fragment)

    <h2>Trust Relationships</h2>
    $($AllResults.TrustRelationships | 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-11)"

    switch ($choice) {
        "1" { $allResults.DomainInfo = Get-DomainInformation }
        "2" { $allResults.DCHealth = Get-DomainControllerHealth }
        "3" { $allResults.UserAnalysis = Get-UserAccountAnalysis }
        "4" { $allResults.GroupAnalysis = Get-GroupAnalysis }
        "5" { $allResults.GPOCheck = Get-GPOCheck }
        "6" { $allResults.DNSHealth = Get-DNSHealthCheck }
        "7" { $allResults.FSMORoles = Get-FSMORolesCheck }
        "8" { $allResults.ReplicationStatus = Get-ReplicationStatus }
        "9" { $allResults.TrustRelationships = Get-TrustRelationships }
        "10" { Generate-HTMLReport -AllResults $allResults }
        "11" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Domain Check Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of the Active Directory domain:
    • Domain Information
    • Domain Controller Health Check
    • User Account Analysis
    • Group Analysis
    • Group Policy Object (GPO) Check
    • DNS Health Check
    • FSMO Roles Check
    • Replication Status
    • Trust Relationships
  3. HTML report generation for easy sharing and viewing of results.

Key features:

  • Comprehensive domain information gathering
  • Health check of all domain controllers
  • Analysis of user accounts, including inactive and potentially insecure accounts
  • Overview of group distribution in the domain
  • GPO inventory and version checking
  • DNS server health verification
  • FSMO roles location check
  • Replication status and failure detection
  • Trust relationship enumeration

This tool is particularly useful for:

  • Domain administrators performing regular health checks
  • IT professionals troubleshooting domain-wide issues
  • Security auditors reviewing domain configurations
  • Anyone needing to quickly gather comprehensive information about an Active Directory domain

To use this script effectively:

  1. Run PowerShell as an administrator on a domain-joined machine (preferably a domain controller)
  2. Ensure you have the necessary permissions to query domain information (Domain Admin or equivalent rights)
  3. Have the Active Directory PowerShell module installed
  4. Review the generated HTML report for a comprehensive overview of the domain’s status and configuration

This script provides a thorough check of an Active Directory domain, helping to identify potential issues, misconfigurations, or security concerns. It’s designed to give administrators a quick but comprehensive view of their domain’s health and configuration.

Local Windows Client Audit Toolkit

<#
.SYNOPSIS
Local Windows Client Audit Toolkit

.DESCRIPTION
This script performs a comprehensive audit of a local Windows client machine,
gathering information about hardware, software, security settings, and more.

.NOTES
File Name      : LocalWindowsClientAuditToolkit.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\LocalWindowsClientAuditToolkit.ps1
#>

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

function Show-Menu {
    Clear-Host
    Write-Host "=== Local Windows Client Audit Toolkit ===" -ForegroundColor Cyan
    Write-Host "1. System Information"
    Write-Host "2. Hardware Inventory"
    Write-Host "3. Installed Software"
    Write-Host "4. Windows Update Status"
    Write-Host "5. Security Settings"
    Write-Host "6. Network Configuration"
    Write-Host "7. User Accounts and Groups"
    Write-Host "8. Startup Programs"
    Write-Host "9. Disk Space and File System"
    Write-Host "10. Event Log Analysis"
    Write-Host "11. Generate Comprehensive HTML Report"
    Write-Host "12. Exit"
}

function Get-SystemInformation {
    Write-Host "`nGathering System Information..." -ForegroundColor Yellow
    $os = Get-CimInstance Win32_OperatingSystem
    $cs = Get-CimInstance Win32_ComputerSystem
    $result = [PSCustomObject]@{
        ComputerName = $env:COMPUTERNAME
        OSName = $os.Caption
        OSVersion = $os.Version
        OSArchitecture = $os.OSArchitecture
        LastBootUpTime = $os.LastBootUpTime
        Manufacturer = $cs.Manufacturer
        Model = $cs.Model
        TotalPhysicalMemory = "{0:N2} GB" -f ($cs.TotalPhysicalMemory / 1GB)
    }
    $result | Format-List
    return $result
}

function Get-HardwareInventory {
    Write-Host "`nGathering Hardware Inventory..." -ForegroundColor Yellow
    $cpu = Get-CimInstance Win32_Processor
    $ram = Get-CimInstance Win32_PhysicalMemory
    $disk = Get-CimInstance Win32_DiskDrive
    $gpu = Get-CimInstance Win32_VideoController

    $result = [PSCustomObject]@{
        CPU = "$($cpu.Name) ($($cpu.NumberOfCores) cores, $($cpu.NumberOfLogicalProcessors) logical processors)"
        RAM = $ram | ForEach-Object { "$($_.Capacity / 1GB) GB $($_.Manufacturer)" }
        Disks = $disk | ForEach-Object { "$($_.Model) ($([math]::Round($_.Size / 1GB)) GB)" }
        GPU = $gpu.Name
    }
    $result | Format-List
    return $result
}

function Get-InstalledSoftware {
    Write-Host "`nGathering Installed Software..." -ForegroundColor Yellow
    $software = Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*,
                                 HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |
                Where-Object { $_.DisplayName -and $_.DisplayName -notmatch '^(Update for|Security Update for|Hotfix for)' } |
                Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
                Sort-Object DisplayName

    $software | Format-Table -AutoSize
    return $software
}

function Get-WindowsUpdateStatus {
    Write-Host "`nChecking Windows Update Status..." -ForegroundColor Yellow
    $updateSession = New-Object -ComObject Microsoft.Update.Session
    $updateSearcher = $updateSession.CreateUpdateSearcher()
    $pendingUpdates = $updateSearcher.Search("IsInstalled=0")

    $lastUpdate = Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 1

    $result = [PSCustomObject]@{
        PendingUpdatesCount = $pendingUpdates.Updates.Count
        LastUpdateDate = $lastUpdate.InstalledOn
        LastUpdateHotfixID = $lastUpdate.HotFixID
    }
    $result | Format-List
    return $result
}

function Get-SecuritySettings {
    Write-Host "`nGathering Security Settings..." -ForegroundColor Yellow
    $firewall = Get-NetFirewallProfile
    $av = Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct
    $uac = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA"

    $result = [PSCustomObject]@{
        FirewallStatus = $firewall | ForEach-Object { "$($_.Name): $($_.Enabled)" }
        AntivirusProduct = $av.displayName
        UACEnabled = if ($uac.EnableLUA -eq 1) { "Enabled" } else { "Disabled" }
    }
    $result | Format-List
    return $result
}

function Get-NetworkConfiguration {
    Write-Host "`nGathering Network Configuration..." -ForegroundColor Yellow
    $adapters = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }
    $result = @()
    foreach ($adapter in $adapters) {
        $ipConfig = Get-NetIPConfiguration -InterfaceIndex $adapter.ifIndex
        $result += [PSCustomObject]@{
            InterfaceName = $adapter.Name
            InterfaceDescription = $adapter.InterfaceDescription
            MACAddress = $adapter.MacAddress
            IPAddress = $ipConfig.IPv4Address.IPAddress
            SubnetMask = $ipConfig.IPv4Address.PrefixLength
            DefaultGateway = $ipConfig.IPv4DefaultGateway.NextHop
            DNSServers = $ipConfig.DNSServer.ServerAddresses -join ", "
        }
    }
    $result | Format-Table -AutoSize
    return $result
}

function Get-UserAccountsAndGroups {
    Write-Host "`nGathering User Accounts and Groups..." -ForegroundColor Yellow
    $users = Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet
    $groups = Get-LocalGroup | Select-Object Name, Description

    $result = [PSCustomObject]@{
        Users = $users
        Groups = $groups
    }
    $result.Users | Format-Table -AutoSize
    $result.Groups | Format-Table -AutoSize
    return $result
}

function Get-StartupPrograms {
    Write-Host "`nGathering Startup Programs..." -ForegroundColor Yellow
    $startupPrograms = Get-CimInstance Win32_StartupCommand | Select-Object Name, Command, Location, User
    $startupPrograms | Format-Table -AutoSize
    return $startupPrograms
}

function Get-DiskSpaceAndFileSystem {
    Write-Host "`nAnalyzing Disk Space and File System..." -ForegroundColor Yellow
    $disks = Get-CimInstance Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
    $result = @()
    foreach ($disk in $disks) {
        $result += [PSCustomObject]@{
            DriveLetter = $disk.DeviceID
            VolumeName = $disk.VolumeName
            FileSystem = $disk.FileSystem
            TotalSpace = "{0:N2} GB" -f ($disk.Size / 1GB)
            FreeSpace = "{0:N2} GB" -f ($disk.FreeSpace / 1GB)
            PercentFree = "{0:N2}%" -f (($disk.FreeSpace / $disk.Size) * 100)
        }
    }
    $result | Format-Table -AutoSize
    return $result
}

function Get-EventLogAnalysis {
    Write-Host "`nAnalyzing Event Logs..." -ForegroundColor Yellow
    $logs = @("System", "Application", "Security")
    $result = @()
    foreach ($log in $logs) {
        $events = Get-EventLog -LogName $log -Newest 100
        $errorCount = ($events | Where-Object { $_.EntryType -eq "Error" }).Count
        $warningCount = ($events | Where-Object { $_.EntryType -eq "Warning" }).Count
        $result += [PSCustomObject]@{
            LogName = $log
            TotalEvents = $events.Count
            ErrorCount = $errorCount
            WarningCount = $warningCount
            MostCommonSource = ($events | Group-Object Source | Sort-Object Count -Descending | Select-Object -First 1).Name
        }
    }
    $result | Format-Table -AutoSize
    return $result
}

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>Windows Client Audit 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; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>Windows Client Audit Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>System Information</h2>
    $($AllResults.SystemInfo | ConvertTo-Html -Fragment)

    <h2>Hardware Inventory</h2>
    $($AllResults.HardwareInventory | ConvertTo-Html -Fragment)

    <h2>Installed Software</h2>
    $($AllResults.InstalledSoftware | ConvertTo-Html -Fragment)

    <h2>Windows Update Status</h2>
    $($AllResults.WindowsUpdateStatus | ConvertTo-Html -Fragment)

    <h2>Security Settings</h2>
    $($AllResults.SecuritySettings | ConvertTo-Html -Fragment)

    <h2>Network Configuration</h2>
    $($AllResults.NetworkConfig | ConvertTo-Html -Fragment)

    <h2>User Accounts and Groups</h2>
    <h3>Users</h3>
    $($AllResults.UserAccountsAndGroups.Users | ConvertTo-Html -Fragment)
    <h3>Groups</h3>
    $($AllResults.UserAccountsAndGroups.Groups | ConvertTo-Html -Fragment)

    <h2>Startup Programs</h2>
    $($AllResults.StartupPrograms | ConvertTo-Html -Fragment)

    <h2>Disk Space and File System</h2>
    $($AllResults.DiskSpace | ConvertTo-Html -Fragment)

    <h2>Event Log Analysis</h2>
    $($AllResults.EventLogAnalysis | 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" { $allResults.SystemInfo = Get-SystemInformation }
        "2" { $allResults.HardwareInventory = Get-HardwareInventory }
        "3" { $allResults.InstalledSoftware = Get-InstalledSoftware }
        "4" { $allResults.WindowsUpdateStatus = Get-WindowsUpdateStatus }
        "5" { $allResults.SecuritySettings = Get-SecuritySettings }
        "6" { $allResults.NetworkConfig = Get-NetworkConfiguration }
        "7" { $allResults.UserAccountsAndGroups = Get-UserAccountsAndGroups }
        "8" { $allResults.StartupPrograms = Get-StartupPrograms }
        "9" { $allResults.DiskSpace = Get-DiskSpaceAndFileSystem }
        "10" { $allResults.EventLogAnalysis = Get-EventLogAnalysis }
        "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 Local Windows Client Audit Toolkit includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to gather various aspects of system information:
    • System Information (OS details, manufacturer, model, etc.)
    • Hardware Inventory (CPU, RAM, disk, GPU)
    • Installed Software
    • Windows Update Status
    • Security Settings (firewall, antivirus, UAC)
    • Network Configuration
    • User Accounts and Groups
    • Startup Programs
    • Disk Space and File System information
    • Event Log Analysis
  3. HTML report generation for easy sharing and viewing of results

Key features:

  • Comprehensive system information gathering
  • Detailed hardware inventory
  • Software inventory including version information
  • Windows update status check
  • Security settings overview
  • Network configuration details
  • User account and group information
  • Startup program listing
  • Disk space analysis
  • Basic event log analysis

This tool is particularly useful for:

  • IT administrators performing system audits
  • Help desk personnel gathering system information
  • System analysts investigating performance or security issues
  • Anyone needing a comprehensive overview of a Windows client machine

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to query system information
  3. Review the generated HTML report for a comprehensive overview of the system

This script provides a thorough audit of a Windows client machine, making it easier to inventory, troubleshoot, or document system configurations. Remember to use this tool responsibly and respect privacy and security policies when auditing systems.