Discover powerful PowerShell programs and scripts to automate tasks, manage systems, and enhance productivity. Learn to create, customize, and implement efficient PowerShell solutions for Windows administration, network management, and more. Explore expert tips, best practices, and real-world examples to master PowerShell programming and streamline your IT operations.

Password Generator Tool

<#
.SYNOPSIS
Password Generator Tool

.DESCRIPTION
This script generates secure passwords based on user-defined criteria including
length, and the inclusion of uppercase letters, lowercase letters, numbers, and special characters.

.NOTES
File Name      : PasswordGenerator.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V3 or later
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\PasswordGenerator.ps1
#>

function Show-Menu {
    Clear-Host
    Write-Host "=== Password Generator Tool ===" -ForegroundColor Cyan
    Write-Host "1. Generate Password"
    Write-Host "2. Set Password Options"
    Write-Host "3. View Current Settings"
    Write-Host "4. Exit"
}

function Set-PasswordOptions {
    $script:passwordLength = Read-Host "Enter password length (default is 12)"
    if ([string]::IsNullOrWhiteSpace($script:passwordLength)) { $script:passwordLength = 12 }
    
    $script:includeUppercase = Read-Host "Include uppercase letters? (Y/N, default is Y)"
    $script:includeUppercase = ($script:includeUppercase -ne 'N')
    
    $script:includeLowercase = Read-Host "Include lowercase letters? (Y/N, default is Y)"
    $script:includeLowercase = ($script:includeLowercase -ne 'N')
    
    $script:includeNumbers = Read-Host "Include numbers? (Y/N, default is Y)"
    $script:includeNumbers = ($script:includeNumbers -ne 'N')
    
    $script:includeSpecialChars = Read-Host "Include special characters? (Y/N, default is Y)"
    $script:includeSpecialChars = ($script:includeSpecialChars -ne 'N')
    
    Write-Host "Password options updated." -ForegroundColor Green
}

function View-CurrentSettings {
    Write-Host "`nCurrent Password Generation Settings:" -ForegroundColor Yellow
    Write-Host "Password Length: $script:passwordLength"
    Write-Host "Include Uppercase: $($script:includeUppercase ? 'Yes' : 'No')"
    Write-Host "Include Lowercase: $($script:includeLowercase ? 'Yes' : 'No')"
    Write-Host "Include Numbers: $($script:includeNumbers ? 'Yes' : 'No')"
    Write-Host "Include Special Characters: $($script:includeSpecialChars ? 'Yes' : 'No')"
    Write-Host ""
}

function Generate-Password {
    $characterSet = @()
    if ($script:includeUppercase) { $characterSet += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.ToCharArray() }
    if ($script:includeLowercase) { $characterSet += 'abcdefghijklmnopqrstuvwxyz'.ToCharArray() }
    if ($script:includeNumbers) { $characterSet += '0123456789'.ToCharArray() }
    if ($script:includeSpecialChars) { $characterSet += '!@#$%^&*()_+-=[]{}|;:,.<>?'.ToCharArray() }

    if ($characterSet.Count -eq 0) {
        Write-Host "Error: No character set selected. Please update your settings." -ForegroundColor Red
        return
    }

    $password = -join (1..$script:passwordLength | ForEach-Object { Get-Random -InputObject $characterSet })
    
    Write-Host "`nGenerated Password:" -ForegroundColor Green
    Write-Host $password
    Write-Host ""

    $saveToFile = Read-Host "Do you want to save this password to a file? (Y/N)"
    if ($saveToFile -eq 'Y') {
        $fileName = "GeneratedPassword_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
        $filePath = Join-Path -Path $env:USERPROFILE -ChildPath "Desktop\$fileName"
        $password | Out-File -FilePath $filePath
        Write-Host "Password saved to: $filePath" -ForegroundColor Green
    }
}

# Initialize default settings
$script:passwordLength = 12
$script:includeUppercase = $true
$script:includeLowercase = $true
$script:includeNumbers = $true
$script:includeSpecialChars = $true

# Main program loop
do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-4)"

    switch ($choice) {
        "1" { Generate-Password }
        "2" { Set-PasswordOptions }
        "3" { View-CurrentSettings }
        "4" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Password Generator Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to:
    • Generate passwords based on user-defined criteria
    • Set password generation options
    • View current password generation settings
  3. Customizable options for password generation:
    • Password length
    • Inclusion of uppercase letters
    • Inclusion of lowercase letters
    • Inclusion of numbers
    • Inclusion of special characters
  4. Option to save generated passwords to a file on the desktop.
  5. Default settings for quick password generation.

Key features:

  • Flexible password generation based on user preferences
  • Ability to customize password complexity
  • Option to save generated passwords securely
  • User-friendly interface for easy operation
  • Viewing current settings for transparency

This tool is particularly useful for:

  • System administrators needing to generate secure passwords
  • Users who want to create strong, customized passwords
  • IT professionals managing password policies
  • Anyone needing quick access to randomly generated passwords

To use this script effectively:

  1. Run the script in PowerShell
  2. Use the menu to navigate between generating passwords, setting options, and viewing current settings
  3. Customize the password generation criteria as needed
  4. Generate passwords and optionally save them to files

This script provides a simple yet effective way to generate secure passwords with customizable criteria, helping to enhance security practices in various IT and personal scenarios.

Windows Firewall Analyzer Tool – Target Computer

<#
.SYNOPSIS
Windows Firewall Analyzer Tool

.DESCRIPTION
This script analyzes and audits Windows Firewall configurations, rules, and profiles
on local or remote Windows systems. It provides insights into firewall settings,
rule configurations, and potential security issues.

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

.EXAMPLE
.\WindowsFirewallAnalyzer.ps1
#>

# Import required module
Import-Module NetSecurity

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Windows Firewall Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "Current Target: $global:targetComputer"
    Write-Host "1. Set Target Computer"
    Write-Host "2. Analyze Firewall Profiles"
    Write-Host "3. Review Inbound Rules"
    Write-Host "4. Review Outbound Rules"
    Write-Host "5. Check for Potentially Risky Rules"
    Write-Host "6. Analyze Rule Applications"
    Write-Host "7. Check Firewall Logging Settings"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Sets the target computer for analysis.
#>
function Set-TargetComputer {
    $computer = Read-Host "Enter the name of the target computer (or press Enter for local machine)"
    if ([string]::IsNullOrWhiteSpace($computer)) {
        $global:targetComputer = $env:COMPUTERNAME
    } else {
        $global:targetComputer = $computer
    }
    Write-Host "Target computer set to: $global:targetComputer" -ForegroundColor Green
}

<#
.SYNOPSIS
Analyzes Firewall Profiles.

.OUTPUTS
Array of PSObjects containing firewall profile details.
#>
function Analyze-FirewallProfiles {
    Write-Host "`nAnalyzing Firewall Profiles..." -ForegroundColor Yellow
    $profiles = Get-NetFirewallProfile -CimSession $global:targetComputer
    $results = @()
    foreach ($profile in $profiles) {
        $results += [PSCustomObject]@{
            Name = $profile.Name
            Enabled = $profile.Enabled
            DefaultInboundAction = $profile.DefaultInboundAction
            DefaultOutboundAction = $profile.DefaultOutboundAction
            AllowInboundRules = $profile.AllowInboundRules
            AllowLocalFirewallRules = $profile.AllowLocalFirewallRules
            AllowLocalIPsecRules = $profile.AllowLocalIPsecRules
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews Inbound Rules.

.OUTPUTS
Array of PSObjects containing inbound rule details.
#>
function Review-InboundRules {
    Write-Host "`nReviewing Inbound Rules..." -ForegroundColor Yellow
    $rules = Get-NetFirewallRule -CimSession $global:targetComputer | Where-Object { $_.Direction -eq "Inbound" }
    $results = @()
    foreach ($rule in $rules) {
        $results += [PSCustomObject]@{
            Name = $rule.Name
            DisplayName = $rule.DisplayName
            Enabled = $rule.Enabled
            Action = $rule.Action
            Profile = $rule.Profile
            Protocol = (Get-NetFirewallPortFilter -AssociatedNetFirewallRule $rule).Protocol
            LocalPort = (Get-NetFirewallPortFilter -AssociatedNetFirewallRule $rule).LocalPort -join ", "
            RemoteAddress = (Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $rule).RemoteAddress -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews Outbound Rules.

.OUTPUTS
Array of PSObjects containing outbound rule details.
#>
function Review-OutboundRules {
    Write-Host "`nReviewing Outbound Rules..." -ForegroundColor Yellow
    $rules = Get-NetFirewallRule -CimSession $global:targetComputer | Where-Object { $_.Direction -eq "Outbound" }
    $results = @()
    foreach ($rule in $rules) {
        $results += [PSCustomObject]@{
            Name = $rule.Name
            DisplayName = $rule.DisplayName
            Enabled = $rule.Enabled
            Action = $rule.Action
            Profile = $rule.Profile
            Protocol = (Get-NetFirewallPortFilter -AssociatedNetFirewallRule $rule).Protocol
            RemotePort = (Get-NetFirewallPortFilter -AssociatedNetFirewallRule $rule).RemotePort -join ", "
            RemoteAddress = (Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $rule).RemoteAddress -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks for Potentially Risky Rules.

.OUTPUTS
Array of PSObjects containing potentially risky rule details.
#>
function Check-PotentiallyRiskyRules {
    Write-Host "`nChecking for Potentially Risky Rules..." -ForegroundColor Yellow
    $rules = Get-NetFirewallRule -CimSession $global:targetComputer
    $results = @()
    foreach ($rule in $rules) {
        $isRisky = $false
        $riskFactors = @()

        if ($rule.Enabled -and $rule.Action -eq "Allow" -and $rule.Direction -eq "Inbound") {
            $portFilter = Get-NetFirewallPortFilter -AssociatedNetFirewallRule $rule
            $addressFilter = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $rule

            if ($portFilter.LocalPort -contains "Any" -or $portFilter.LocalPort -contains "*") {
                $isRisky = $true
                $riskFactors += "Allows any port"
            }
            if ($addressFilter.RemoteAddress -contains "Any" -or $addressFilter.RemoteAddress -contains "*") {
                $isRisky = $true
                $riskFactors += "Allows any remote address"
            }
        }

        if ($isRisky) {
            $results += [PSCustomObject]@{
                Name = $rule.Name
                DisplayName = $rule.DisplayName
                Direction = $rule.Direction
                Action = $rule.Action
                RiskFactors = $riskFactors -join ", "
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Rule Applications.

.OUTPUTS
Array of PSObjects containing rule application details.
#>
function Analyze-RuleApplications {
    Write-Host "`nAnalyzing Rule Applications..." -ForegroundColor Yellow
    $rules = Get-NetFirewallRule -CimSession $global:targetComputer
    $results = @()
    foreach ($rule in $rules) {
        $appFilter = Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $rule
        if ($appFilter.Program -and $appFilter.Program -ne "Any") {
            $results += [PSCustomObject]@{
                RuleName = $rule.Name
                DisplayName = $rule.DisplayName
                Application = $appFilter.Program
                Enabled = $rule.Enabled
                Direction = $rule.Direction
                Action = $rule.Action
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Firewall Logging Settings.

.OUTPUTS
PSObject containing firewall logging settings.
#>
function Check-FirewallLoggingSettings {
    Write-Host "`nChecking Firewall Logging Settings..." -ForegroundColor Yellow
    $profiles = Get-NetFirewallProfile -CimSession $global:targetComputer
    $results = @()
    foreach ($profile in $profiles) {
        $results += [PSCustomObject]@{
            ProfileName = $profile.Name
            LogAllowed = $profile.LogAllowed
            LogBlocked = $profile.LogBlocked
            LogIgnored = $profile.LogIgnored
            LogFileName = $profile.LogFileName
            LogMaxSizeKilobytes = $profile.LogMaxSizeKilobytes
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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 Firewall 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>Windows Firewall Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>Target Computer: $global:targetComputer</p>

    <h2>Firewall Profiles</h2>
    $($AllResults.FirewallProfiles | ConvertTo-Html -Fragment)

    <h2>Inbound Rules</h2>
    $($AllResults.InboundRules | ConvertTo-Html -Fragment)

    <h2>Outbound Rules</h2>
    $($AllResults.OutboundRules | ConvertTo-Html -Fragment)

    <h2>Potentially Risky Rules</h2>
    $($AllResults.RiskyRules | ConvertTo-Html -Fragment)

    <h2>Rule Applications</h2>
    $($AllResults.RuleApplications | ConvertTo-Html -Fragment)

    <h2>Firewall Logging Settings</h2>
    $($AllResults.LoggingSettings | 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-9)"

    switch ($choice) {
        "1" { Set-TargetComputer }
        "2" { $allResults.FirewallProfiles = Analyze-FirewallProfiles }
        "3" { $allResults.InboundRules = Review-InboundRules }
        "4" { $allResults.OutboundRules = Review-OutboundRules }
        "5" { $allResults.RiskyRules = Check-PotentiallyRiskyRules }
        "6" { $allResults.RuleApplications = Analyze-RuleApplications }
        "7" { $allResults.LoggingSettings = Check-FirewallLoggingSettings }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Windows Firewall Analyzer Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of Windows Firewall:
    • Analysis of Firewall Profiles
    • Review of Inbound Rules
    • Review of Outbound Rules
    • Check for Potentially Risky Rules
    • Analysis of Rule Applications
    • Check Firewall Logging Settings
  3. Ability to set a target computer for remote analysis.
  4. Comprehensive error handling for each analysis function.
  5. A function to generate an HTML report of all collected data.

Key features:

  • Detailed analysis of Windows Firewall profiles and their settings
  • Comprehensive review of inbound and outbound firewall rules
  • Identification of potentially risky firewall rules
  • Analysis of application-specific firewall rules
  • Review of firewall logging settings
  • Support for local and remote firewall analysis
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • System administrators managing Windows Firewall configurations
  • Security professionals auditing firewall settings
  • IT professionals troubleshooting firewall-related issues
  • Network administrators reviewing firewall rules across multiple systems

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to access firewall settings (local or remote)
  3. Have the NetSecurity module available (typically included in Windows by default)

This script provides a comprehensive overview of Windows Firewall configurations, making it easier to audit and maintain firewall settings, identify potential security issues, and ensure the proper configuration of firewall rules across Windows systems.

Microsoft 365 Security Check Tool

<#
.SYNOPSIS
Microsoft 365 Security Check Tool

.DESCRIPTION
This script analyzes and audits various security aspects of a Microsoft 365 environment,
providing insights into user accounts, licenses, Exchange Online, SharePoint Online,
Teams, and other security settings.

.NOTES
File Name      : M365SecurityCheckTool.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, Microsoft 365 PowerShell modules, and appropriate admin permissions
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\M365SecurityCheckTool.ps1
#>

# Check and install required modules
$requiredModules = @("MSOnline", "ExchangeOnlineManagement", "Microsoft.Online.SharePoint.PowerShell", "MicrosoftTeams", "AzureAD")
foreach ($module in $requiredModules) {
    if (!(Get-Module -ListAvailable -Name $module)) {
        Write-Host "Installing $module module..." -ForegroundColor Yellow
        Install-Module -Name $module -Force -AllowClobber
    }
}

# Import required modules
Import-Module MSOnline
Import-Module ExchangeOnlineManagement
Import-Module Microsoft.Online.SharePoint.PowerShell
Import-Module MicrosoftTeams
Import-Module AzureAD

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Microsoft 365 Security Check Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze User Accounts and MFA Status"
    Write-Host "2. Check License Assignments"
    Write-Host "3. Analyze Exchange Online Security Settings"
    Write-Host "4. Check SharePoint Online and OneDrive Security"
    Write-Host "5. Analyze Teams Security Settings"
    Write-Host "6. Check Azure AD Security Configuration"
    Write-Host "7. Analyze Conditional Access Policies"
    Write-Host "8. Check Data Loss Prevention Policies"
    Write-Host "9. Analyze Audit Log Settings"
    Write-Host "10. Generate Comprehensive HTML Report"
    Write-Host "11. Exit"
}

<#
.SYNOPSIS
Connects to Microsoft 365 services.
#>
function Connect-M365Services {
    Write-Host "Connecting to Microsoft 365 services..." -ForegroundColor Yellow
    Connect-MsolService
    Connect-ExchangeOnline
    $orgName = (Get-MsolCompanyInformation).DisplayName
    $adminSiteUrl = "https://$($orgName.Replace(' ', ''))-admin.sharepoint.com"
    Connect-SPOService -Url $adminSiteUrl
    Connect-MicrosoftTeams
    Connect-AzureAD
}

<#
.SYNOPSIS
Analyzes user accounts and MFA status.

.OUTPUTS
Array of PSObjects containing user account and MFA details.
#>
function Analyze-UserAccountsAndMFA {
    Write-Host "`nAnalyzing User Accounts and MFA Status..." -ForegroundColor Yellow
    $users = Get-MsolUser -All
    $results = @()
    foreach ($user in $users) {
        $mfaStatus = if ($user.StrongAuthenticationRequirements.State) { $user.StrongAuthenticationRequirements.State } else { "Disabled" }
        $results += [PSCustomObject]@{
            UserPrincipalName = $user.UserPrincipalName
            DisplayName = $user.DisplayName
            IsLicensed = $user.IsLicensed
            MFAStatus = $mfaStatus
            LastPasswordChangeTimestamp = $user.LastPasswordChangeTimestamp
            BlockCredential = $user.BlockCredential
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks license assignments.

.OUTPUTS
Array of PSObjects containing license assignment details.
#>
function Check-LicenseAssignments {
    Write-Host "`nChecking License Assignments..." -ForegroundColor Yellow
    $licenses = Get-MsolAccountSku
    $results = @()
    foreach ($license in $licenses) {
        $results += [PSCustomObject]@{
            AccountSkuId = $license.AccountSkuId
            ActiveUnits = $license.ActiveUnits
            ConsumedUnits = $license.ConsumedUnits
            AvailableUnits = ($license.ActiveUnits - $license.ConsumedUnits)
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Exchange Online security settings.

.OUTPUTS
PSObject containing Exchange Online security settings.
#>
function Analyze-ExchangeOnlineSecurity {
    Write-Host "`nAnalyzing Exchange Online Security Settings..." -ForegroundColor Yellow
    $transportRules = Get-TransportRule
    $malwareFilterPolicy = Get-MalwareFilterPolicy
    $result = [PSCustomObject]@{
        TransportRuleCount = $transportRules.Count
        MalwareFilterEnabled = $malwareFilterPolicy.Enabled
        AuditLogEnabled = (Get-AdminAuditLogConfig).UnifiedAuditLogIngestionEnabled
        DefaultAuthenticationPolicy = (Get-OrganizationConfig).DefaultAuthenticationPolicy
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Checks SharePoint Online and OneDrive security.

.OUTPUTS
PSObject containing SharePoint Online and OneDrive security settings.
#>
function Check-SharePointOneDriveSecurity {
    Write-Host "`nChecking SharePoint Online and OneDrive Security..." -ForegroundColor Yellow
    $sharingCapability = Get-SPOTenant | Select-Object SharingCapability
    $conditionalAccessPolicy = Get-SPOTenant | Select-Object ConditionalAccessPolicy
    $result = [PSCustomObject]@{
        SharingCapability = $sharingCapability.SharingCapability
        ConditionalAccessPolicy = $conditionalAccessPolicy.ConditionalAccessPolicy
        OneDriveForBusinessSharingCapability = (Get-SPOTenant).OneDriveForBusinessSharingCapability
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Analyzes Teams security settings.

.OUTPUTS
PSObject containing Teams security settings.
#>
function Analyze-TeamsSecuritySettings {
    Write-Host "`nAnalyzing Teams Security Settings..." -ForegroundColor Yellow
    $teamsSettings = Get-CsTeamsClientConfiguration
    $result = [PSCustomObject]@{
        AllowEmailIntoChannel = $teamsSettings.AllowEmailIntoChannel
        AllowDropBox = $teamsSettings.AllowDropBox
        AllowBox = $teamsSettings.AllowBox
        AllowGoogleDrive = $teamsSettings.AllowGoogleDrive
        AllowShareFile = $teamsSettings.AllowShareFile
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Checks Azure AD security configuration.

.OUTPUTS
PSObject containing Azure AD security configuration.
#>
function Check-AzureADSecurityConfig {
    Write-Host "`nChecking Azure AD Security Configuration..." -ForegroundColor Yellow
    $passwordPolicy = Get-MsolPasswordPolicy -TenantId (Get-MsolCompanyInformation).ObjectId
    $ssoState = (Get-MsolCompanyInformation).SelfServePasswordResetEnabled
    $result = [PSCustomObject]@{
        PasswordValidityPeriod = $passwordPolicy.ValidityPeriod
        MinimumPasswordLength = $passwordPolicy.MinimumPasswordLength
        PasswordComplexityEnabled = $passwordPolicy.StrongPasswordRequired
        SelfServicePasswordResetEnabled = $ssoState
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Analyzes Conditional Access Policies.

.OUTPUTS
Array of PSObjects containing Conditional Access Policy details.
#>
function Analyze-ConditionalAccessPolicies {
    Write-Host "`nAnalyzing Conditional Access Policies..." -ForegroundColor Yellow
    $policies = Get-AzureADMSConditionalAccessPolicy
    $results = @()
    foreach ($policy in $policies) {
        $results += [PSCustomObject]@{
            DisplayName = $policy.DisplayName
            State = $policy.State
            IncludeUsers = $policy.Conditions.Users.IncludeUsers -join ", "
            ExcludeUsers = $policy.Conditions.Users.ExcludeUsers -join ", "
            IncludeApplications = $policy.Conditions.Applications.IncludeApplications -join ", "
            GrantControls = $policy.GrantControls.BuiltInControls -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Data Loss Prevention Policies.

.OUTPUTS
Array of PSObjects containing DLP Policy details.
#>
function Check-DLPPolicies {
    Write-Host "`nChecking Data Loss Prevention Policies..." -ForegroundColor Yellow
    $policies = Get-DlpCompliancePolicy
    $results = @()
    foreach ($policy in $policies) {
        $results += [PSCustomObject]@{
            Name = $policy.Name
            Mode = $policy.Mode
            Enabled = $policy.Enabled
            ExchangeLocation = $policy.ExchangeLocation -join ", "
            SharePointLocation = $policy.SharePointLocation -join ", "
            OneDriveLocation = $policy.OneDriveLocation -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Audit Log Settings.

.OUTPUTS
PSObject containing Audit Log settings.
#>
function Analyze-AuditLogSettings {
    Write-Host "`nAnalyzing Audit Log Settings..." -ForegroundColor Yellow
    $auditConfig = Get-AdminAuditLogConfig
    $result = [PSCustomObject]@{
        UnifiedAuditLogIngestionEnabled = $auditConfig.UnifiedAuditLogIngestionEnabled
        OperationsToLog = $auditConfig.AdminAuditLogCmdlets -join ", "
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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>Microsoft 365 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>Microsoft 365 Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>User Accounts and MFA Status</h2>
    $($AllResults.UserAccountsAndMFA | ConvertTo-Html -Fragment)

    <h2>License Assignments</h2>
    $($AllResults.LicenseAssignments | ConvertTo-Html -Fragment)

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

    <h2>SharePoint Online and OneDrive Security</h2>
    $($AllResults.SharePointOneDriveSecurity | ConvertTo-Html -Fragment)

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

    <h2>Azure AD Security Configuration</h2>
    $($AllResults.AzureADSecurityConfig | ConvertTo-Html -Fragment)

    <h2>Conditional Access Policies</h2>
    $($AllResults.ConditionalAccessPolicies | ConvertTo-Html -Fragment)

    <h2>Data Loss Prevention Policies</h2>
    $($AllResults.DLPPolicies | ConvertTo-Html -Fragment)

    <h2>Audit Log Settings</h2>
    $($AllResults.AuditLogSettings | 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
Connect-M365Services
$allResults = @{}

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

    switch ($choice) {
        "1" { $allResults.UserAccountsAndMFA = Analyze-UserAccountsAndMFA }
        "2" { $allResults.LicenseAssignments = Check-LicenseAssignments }
        "3" { $allResults.ExchangeOnlineSecurity = Analyze-ExchangeOnlineSecurity }
        "4" { $allResults.SharePointOneDriveSecurity = Check-SharePointOneDriveSecurity }
        "5" { $allResults.TeamsSecuritySettings = Analyze-TeamsSecuritySettings }
        "6" { $allResults.AzureADSecurityConfig = Check-AzureADSecurityConfig }
        "7" { $allResults.ConditionalAccessPolicies = Analyze-ConditionalAccessPolicies }
        "8" { $allResults.DLPPolicies = Check-DLPPolicies }
        "9" { $allResults.AuditLogSettings = Analyze-AuditLogSettings }
        "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")

# Disconnect from services
Disconnect-ExchangeOnline -Confirm:$false
Disconnect-SPOService
Disconnect-MicrosoftTeams
Disconnect-AzureAD

This Microsoft 365 Security Check Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various security aspects of Microsoft 365:
    • User account analysis and MFA status
    • License assignment check
    • Exchange Online security settings analysis
    • SharePoint Online and OneDrive security check
    • Teams security settings analysis
    • Azure AD security configuration check
    • Conditional Access Policies analysis
    • Data Loss Prevention Policies check
    • Audit Log settings analysis
  3. Automatic installation of required PowerShell modules.
  4. Connection to necessary Microsoft 365 services.
  5. A function to generate an HTML report of all collected data.

Key features:

  • Comprehensive analysis of user accounts, including MFA status
  • Detailed insights into license assignments and usage
  • Review of Exchange Online, SharePoint Online, and OneDrive security settings
  • Analysis of Teams security configuration
  • Azure AD security settings check
  • Examination of Conditional Access and DLP policies
  • Audit log configuration review
  • HTML report generation for easy sharing and viewing of results

This tool is particularly useful for:

  • Microsoft 365 administrators
  • IT security professionals managing Microsoft 365 environments
  • Compliance officers ensuring adherence to security standards
  • Anyone needing to perform a security audit of their Microsoft 365 environment

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to access Microsoft 365 services (Global Administrator or appropriate admin roles)
  3. Have an active internet connection
  4. Review the generated HTML report for a comprehensive overview of your Microsoft 365 environment’s security status

This script provides a comprehensive overview of the security settings in a Microsoft 365 environment, making it easier to identify potential security issues, misconfigurations, or areas that need attention across various Microsoft 365 services.

Advanced Security Analyzer Tool for Windows Server

<#
.SYNOPSIS
Advanced Security Analyzer Tool for Windows Server

.DESCRIPTION
This script performs a comprehensive security analysis on a Windows Server,
providing detailed insights into various security aspects and potential vulnerabilities.

.NOTES
File Name      : AdvancedWindowsServerSecurityAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights on a Windows Server
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\AdvancedWindowsServerSecurityAnalyzer.ps1
#>

# Import required modules
Import-Module ActiveDirectory
Import-Module GroupPolicy

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Advanced Windows Server Security Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1.  Analyze Windows Updates and Patches"
    Write-Host "2.  Audit User Accounts and Permissions"
    Write-Host "3.  Check Firewall and Network Security"
    Write-Host "4.  Review File System and Share Permissions"
    Write-Host "5.  Analyze Services and Running Processes"
    Write-Host "6.  Check Group Policy Settings"
    Write-Host "7.  Audit Event Logs"
    Write-Host "8.  Analyze Installed Software"
    Write-Host "9.  Check for Common Vulnerabilities"
    Write-Host "10. Review Encryption and Certificate Settings"
    Write-Host "11. Generate Comprehensive HTML Report"
    Write-Host "12. Exit"
}

<#
.SYNOPSIS
Analyzes Windows Updates and Patches.

.OUTPUTS
PSObject containing Windows Updates and Patch status.
#>
function Analyze-WindowsUpdatesAndPatches {
    Write-Host "`nAnalyzing Windows Updates and Patches..." -ForegroundColor Yellow
    $updateSession = New-Object -ComObject Microsoft.Update.Session
    $updateSearcher = $updateSession.CreateUpdateSearcher()
    $pendingUpdates = $updateSearcher.Search("IsInstalled=0")
    $installedUpdates = Get-HotFix | Sort-Object -Property InstalledOn -Descending

    $result = [PSCustomObject]@{
        PendingUpdatesCount = $pendingUpdates.Updates.Count
        LastUpdateDate = $installedUpdates[0].InstalledOn
        CriticalUpdatesCount = ($pendingUpdates.Updates | Where-Object { $_.MsrcSeverity -eq "Critical" }).Count
        RecentlyInstalledUpdates = $installedUpdates | Select-Object -First 5 | ForEach-Object { "$($_.HotFixID) - $($_.InstalledOn)" }
    }

    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Audits User Accounts and Permissions.

.OUTPUTS
Array of PSObjects containing user account and permission details.
#>
function Audit-UserAccountsAndPermissions {
    Write-Host "`nAuditing User Accounts and Permissions..." -ForegroundColor Yellow
    $users = Get-ADUser -Filter * -Properties Enabled, PasswordLastSet, LastLogonDate, PasswordNeverExpires, MemberOf
    $results = @()
    foreach ($user in $users) {
        $adminGroups = $user.MemberOf | Where-Object { $_ -like "*admin*" }
        $results += [PSCustomObject]@{
            Username = $user.SamAccountName
            Enabled = $user.Enabled
            PasswordLastSet = $user.PasswordLastSet
            LastLogon = $user.LastLogonDate
            PasswordNeverExpires = $user.PasswordNeverExpires
            InAdminGroup = if ($adminGroups) { $true } else { $false }
            AdminGroups = $adminGroups -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Firewall and Network Security.

.OUTPUTS
PSObject containing firewall and network security details.
#>
function Check-FirewallAndNetworkSecurity {
    Write-Host "`nChecking Firewall and Network Security..." -ForegroundColor Yellow
    $firewallProfiles = Get-NetFirewallProfile
    $openPorts = Get-NetTCPConnection | Where-Object { $_.State -eq 'Listen' }
    
    $result = [PSCustomObject]@{
        DomainProfileEnabled = ($firewallProfiles | Where-Object { $_.Name -eq "Domain" }).Enabled
        PrivateProfileEnabled = ($firewallProfiles | Where-Object { $_.Name -eq "Private" }).Enabled
        PublicProfileEnabled = ($firewallProfiles | Where-Object { $_.Name -eq "Public" }).Enabled
        OpenPorts = $openPorts | Select-Object LocalPort, OwningProcess
        InboundRulesCount = (Get-NetFirewallRule -Direction Inbound).Count
        OutboundRulesCount = (Get-NetFirewallRule -Direction Outbound).Count
    }
    
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Reviews File System and Share Permissions.

.OUTPUTS
Array of PSObjects containing file system and share permission details.
#>
function Review-FileSystemAndSharePermissions {
    Write-Host "`nReviewing File System and Share Permissions..." -ForegroundColor Yellow
    $shares = Get-SmbShare | Where-Object { $_.Name -notlike "*$" }
    $results = @()
    foreach ($share in $shares) {
        $acl = Get-Acl $share.Path
        $permissions = $acl.Access | ForEach-Object {
            "$($_.IdentityReference) - $($_.FileSystemRights)"
        }
        $results += [PSCustomObject]@{
            ShareName = $share.Name
            Path = $share.Path
            Permissions = $permissions -join "; "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Services and Running Processes.

.OUTPUTS
Array of PSObjects containing service and process details.
#>
function Analyze-ServicesAndProcesses {
    Write-Host "`nAnalyzing Services and Running Processes..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Running' }
    $processes = Get-Process | Where-Object { $_.CPU -gt 10 -or $_.WorkingSet -gt 100MB }
    
    $results = @()
    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Type = "Service"
            Name = $service.Name
            DisplayName = $service.DisplayName
            StartName = $service.StartName
            State = $service.State
        }
    }
    foreach ($process in $processes) {
        $results += [PSCustomObject]@{
            Type = "Process"
            Name = $process.Name
            ID = $process.Id
            CPU = $process.CPU
            Memory = [math]::Round($process.WorkingSet / 1MB, 2)
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Group Policy Settings.

.OUTPUTS
Array of PSObjects containing Group Policy setting details.
#>
function Check-GroupPolicySettings {
    Write-Host "`nChecking Group Policy Settings..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $results = @()
    foreach ($gpo in $gpos) {
        $report = Get-GPOReport -Guid $gpo.Id -ReportType XML
        $settingsCount = ([xml]$report).GPO.Computer.ExtensionData.Extension.Policy.Count + 
                         ([xml]$report).GPO.User.ExtensionData.Extension.Policy.Count
        $results += [PSCustomObject]@{
            Name = $gpo.DisplayName
            CreationTime = $gpo.CreationTime
            ModificationTime = $gpo.ModificationTime
            SettingsCount = $settingsCount
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Audits Event Logs.

.OUTPUTS
Array of PSObjects containing event log details.
#>
function Audit-EventLogs {
    Write-Host "`nAuditing Event Logs..." -ForegroundColor Yellow
    $logs = @("System", "Security", "Application")
    $results = @()
    foreach ($log in $logs) {
        $events = Get-EventLog -LogName $log -Newest 100 | Group-Object -Property EntryType
        foreach ($eventType in $events) {
            $results += [PSCustomObject]@{
                LogName = $log
                EventType = $eventType.Name
                Count = $eventType.Count
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Installed Software.

.OUTPUTS
Array of PSObjects containing installed software details.
#>
function Analyze-InstalledSoftware {
    Write-Host "`nAnalyzing Installed Software..." -ForegroundColor Yellow
    $software = Get-WmiObject -Class Win32_Product | Select-Object Name, Vendor, Version, InstallDate
    $software | Format-Table -AutoSize
    return $software
}

<#
.SYNOPSIS
Checks for Common Vulnerabilities.

.OUTPUTS
Array of PSObjects containing vulnerability check results.
#>
function Check-CommonVulnerabilities {
    Write-Host "`nChecking for Common Vulnerabilities..." -ForegroundColor Yellow
    $results = @()

    # Check for SMBv1
    $smbv1 = Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol
    $results += [PSCustomObject]@{
        Check = "SMBv1 Enabled"
        Status = if ($smbv1.State -eq "Enabled") { "Vulnerable" } else { "Secure" }
    }

    # Check for PowerShell v2
    $psv2 = Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2
    $results += [PSCustomObject]@{
        Check = "PowerShell v2 Enabled"
        Status = if ($psv2.State -eq "Enabled") { "Vulnerable" } else { "Secure" }
    }

    # Check RDP settings
    $rdpEnabled = (Get-ItemProperty "HKLM:\System\CurrentControlSet\Control\Terminal Server").fDenyTSConnections -eq 0
    $nlaEnabled = (Get-ItemProperty "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp").UserAuthentication -eq 1
    $results += [PSCustomObject]@{
        Check = "RDP Enabled without NLA"
        Status = if ($rdpEnabled -and -not $nlaEnabled) { "Vulnerable" } else { "Secure" }
    }

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

<#
.SYNOPSIS
Reviews Encryption and Certificate Settings.

.OUTPUTS
PSObject containing encryption and certificate details.
#>
function Review-EncryptionAndCertificates {
    Write-Host "`nReviewing Encryption and Certificate Settings..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine\My
    $tlsSettings = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\*\*' | Where-Object { $_.Enabled -ne $null }

    $result = [PSCustomObject]@{
        CertificateCount = $certs.Count
        ExpiredCertificates = ($certs | Where-Object { $_.NotAfter -lt (Get-Date) }).Count
        TLS10Enabled = ($tlsSettings | Where-Object { $_.PSPath -like "*TLS 1.0*" -and $_.Enabled -eq 1 }) -ne $null
        TLS11Enabled = ($tlsSettings | Where-Object { $_.PSPath -like "*TLS 1.1*" -and $_.Enabled -eq 1 }) -ne $null
        TLS12Enabled = ($tlsSettings | Where-Object { $_.PSPath -like "*TLS 1.2*" -and $_.Enabled -eq 1 }) -ne $null
    }

    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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 Windows 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; }
        .vulnerable { color: red; font-weight: bold; }
        .secure { color: green; }
    </style>
</head>
<body>
    <h1>Advanced Windows Server Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>Windows Updates and Patches</h2>
    $($AllResults.UpdatesAndPatches | ConvertTo-Html -Fragment)

    <h2>User Accounts and Permissions</h2>
    $($AllResults.UserAccounts | ConvertTo-Html -Fragment)

    <h2>Firewall and Network Security</h2>
    $($AllResults.FirewallSecurity | ConvertTo-Html -Fragment)

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

    <h2>Services and Running Processes</h2>
    $($AllResults.ServicesAndProcesses | ConvertTo-Html -Fragment)

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

    <h2>Event Logs Summary</h2>
    $($AllResults.EventLogs | ConvertTo-Html -Fragment)

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

    <h2>Common Vulnerabilities Check</h2>
    $($AllResults.Vulnerabilities | ForEach-Object {
        $_.Status = if ($_.Status -eq "Vulnerable") { '<span class="vulnerable">Vulnerable</span>' } else { '<span class="secure">Secure</span>' }
        $_
    } | ConvertTo-Html -Fragment)

    <h2>Encryption and Certificate Settings</h2>
    $($AllResults.EncryptionSettings | 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.UpdatesAndPatches = Analyze-WindowsUpdatesAndPatches }
        "2"  { $allResults.UserAccounts = Audit-UserAccountsAndPermissions }
        "3"  { $allResults.FirewallSecurity = Check-FirewallAndNetworkSecurity }
        "4"  { $allResults.FileSystemPermissions = Review-FileSystemAndSharePermissions }
        "5"  { $allResults.ServicesAndProcesses = Analyze-ServicesAndProcesses }
        "6"  { $allResults.GroupPolicySettings = Check-GroupPolicySettings }
        "7"  { $allResults.EventLogs = Audit-EventLogs }
        "8"  { $allResults.InstalledSoftware = Analyze-InstalledSoftware }
        "9"  { $allResults.Vulnerabilities = Check-CommonVulnerabilities }
        "10" { $allResults.EncryptionSettings = Review-EncryptionAndCertificates }
        "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 Advanced Security Analyzer Tool for Windows Server includes:

  1. A comprehensive menu-driven interface.
  2. Advanced functions to analyze various security aspects:
    • Detailed Windows Updates and Patch analysis
    • In-depth user account and permission auditing
    • Comprehensive firewall and network security check
    • Detailed file system and share permissions review
    • Analysis of services and running processes
    • Group Policy settings check
    • Event log auditing
    • Installed software analysis
    • Common vulnerabilities check
    • Encryption and certificate settings review
  3. Detailed HTML report generation with color-coded vulnerability indicators.

Key features:

  • Comprehensive analysis of Windows Updates, including pending and critical updates
  • Detailed user account analysis, including admin group memberships
  • In-depth firewall analysis, including open ports and rule counts
  • File system and share permission auditing
  • Service and process analysis with focus on auto-start services and resource-intensive processes
  • Group Policy analysis
  • Event log summary for system, security, and application logs
  • Installed software inventory
  • Checks for common vulnerabilities like SMBv1, PowerShell v2, and insecure RDP settings
  • Review of encryption settings and certificate status

This tool is particularly useful for:

  • System administrators performing thorough security audits
  • IT security professionals conducting in-depth security assessments
  • Compliance officers ensuring adherence to security standards
  • Anyone needing a comprehensive overview of a Windows Server’s security posture

To use this script effectively:

  1. Run PowerShell as an administrator on the Windows Server you want to analyze
  2. Ensure you have the necessary permissions to query system information and Active Directory (if applicable)
  3. Review the generated HTML report for a detailed overview of the server’s security status

This script provides a comprehensive and advanced way to analyze the security of a Windows Server, helping to identify potential security issues, misconfigurations, and vulnerabilities across various aspects of the system.

Simple Security Analyzer Tool for Windows Server

<#
.SYNOPSIS
Simple Security Analyzer Tool for Windows Server

.DESCRIPTION
This script analyzes basic security settings and configurations on a Windows Server,
providing insights into potential security issues and misconfigurations.

.NOTES
File Name      : WindowsServerSecurityAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights on a Windows Server
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\WindowsServerSecurityAnalyzer.ps1
#>

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Windows Server Security Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Check Windows Updates Status"
    Write-Host "2. Analyze User Accounts"
    Write-Host "3. Check Firewall Status"
    Write-Host "4. Review Shared Folders"
    Write-Host "5. Check Services Running as SYSTEM"
    Write-Host "6. Analyze Password Policy"
    Write-Host "7. Check for Unquoted Service Paths"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Checks Windows Updates status.

.OUTPUTS
PSObject containing Windows Updates status.
#>
function Check-WindowsUpdates {
    Write-Host "`nChecking Windows Updates 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
}

<#
.SYNOPSIS
Analyzes user accounts.

.OUTPUTS
Array of PSObjects containing user account details.
#>
function Analyze-UserAccounts {
    Write-Host "`nAnalyzing User Accounts..." -ForegroundColor Yellow
    $users = Get-LocalUser
    $results = @()
    foreach ($user in $users) {
        $results += [PSCustomObject]@{
            Username = $user.Name
            Enabled = $user.Enabled
            PasswordExpires = $user.PasswordExpires
            LastLogon = $user.LastLogon
            PasswordRequired = $user.PasswordRequired
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks firewall status.

.OUTPUTS
PSObject containing firewall status.
#>
function Check-FirewallStatus {
    Write-Host "`nChecking Firewall Status..." -ForegroundColor Yellow
    $firewallProfiles = Get-NetFirewallProfile
    $result = [PSCustomObject]@{
        DomainProfile = ($firewallProfiles | Where-Object { $_.Name -eq "Domain" }).Enabled
        PrivateProfile = ($firewallProfiles | Where-Object { $_.Name -eq "Private" }).Enabled
        PublicProfile = ($firewallProfiles | Where-Object { $_.Name -eq "Public" }).Enabled
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Reviews shared folders.

.OUTPUTS
Array of PSObjects containing shared folder details.
#>
function Review-SharedFolders {
    Write-Host "`nReviewing Shared Folders..." -ForegroundColor Yellow
    $shares = Get-SmbShare | Where-Object { $_.Name -notlike "*$" }
    $results = @()
    foreach ($share in $shares) {
        $results += [PSCustomObject]@{
            Name = $share.Name
            Path = $share.Path
            Description = $share.Description
            AccessBasedEnumerationEnabled = $share.FolderEnumerationMode
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks services running as SYSTEM.

.OUTPUTS
Array of PSObjects containing service details.
#>
function Check-SystemServices {
    Write-Host "`nChecking Services Running as SYSTEM..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service | Where-Object { $_.StartName -eq "LocalSystem" }
    $results = @()
    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Name = $service.Name
            DisplayName = $service.DisplayName
            StartMode = $service.StartMode
            State = $service.State
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes password policy.

.OUTPUTS
PSObject containing password policy details.
#>
function Analyze-PasswordPolicy {
    Write-Host "`nAnalyzing Password Policy..." -ForegroundColor Yellow
    $policy = Get-LocalSecurityPolicy
    $result = [PSCustomObject]@{
        PasswordHistorySize = $policy.'PasswordHistorySize'
        MaximumPasswordAge = $policy.'MaximumPasswordAge'
        MinimumPasswordAge = $policy.'MinimumPasswordAge'
        MinimumPasswordLength = $policy.'MinimumPasswordLength'
        PasswordComplexity = $policy.'PasswordComplexity'
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Checks for unquoted service paths.

.OUTPUTS
Array of PSObjects containing services with unquoted paths.
#>
function Check-UnquotedServicePaths {
    Write-Host "`nChecking for Unquoted Service Paths..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service | Where-Object { $_.PathName -notlike '"*"' -and $_.PathName -like '* *' }
    $results = @()
    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Name = $service.Name
            DisplayName = $service.DisplayName
            PathName = $service.PathName
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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 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; }
    </style>
</head>
<body>
    <h1>Windows Server Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

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

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

    <h2>Firewall Status</h2>
    $($AllResults.FirewallStatus | ConvertTo-Html -Fragment)

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

    <h2>Services Running as SYSTEM</h2>
    $($AllResults.SystemServices | ConvertTo-Html -Fragment)

    <h2>Password Policy</h2>
    $($AllResults.PasswordPolicy | ConvertTo-Html -Fragment)

    <h2>Unquoted Service Paths</h2>
    $($AllResults.UnquotedServicePaths | 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-9)"

    switch ($choice) {
        "1" { $allResults.WindowsUpdates = Check-WindowsUpdates }
        "2" { $allResults.UserAccounts = Analyze-UserAccounts }
        "3" { $allResults.FirewallStatus = Check-FirewallStatus }
        "4" { $allResults.SharedFolders = Review-SharedFolders }
        "5" { $allResults.SystemServices = Check-SystemServices }
        "6" { $allResults.PasswordPolicy = Analyze-PasswordPolicy }
        "7" { $allResults.UnquotedServicePaths = Check-UnquotedServicePaths }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Simple Security Analyzer Tool for Windows Server includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various security aspects:
    • Windows Updates status
    • User account analysis
    • Firewall status check
    • Shared folder review
    • Services running as SYSTEM
    • Password policy analysis
    • Check for unquoted service paths
  3. HTML report generation for all collected data.

Key features:

  • Quick overview of pending Windows Updates
  • Analysis of local user accounts and their settings
  • Firewall status check for all profiles
  • Review of non-default shared folders
  • Identification of services running with high privileges (SYSTEM)
  • Password policy review
  • Detection of potential vulnerabilities like unquoted service paths
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • System administrators performing quick security checks
  • IT professionals conducting basic security audits
  • Anyone needing to get a quick overview of a Windows Server’s security posture

To use this script effectively:

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

This script provides a simple yet effective way to perform basic security checks on a Windows Server, helping to identify potential security issues and misconfigurations quickly.

Comprehensive Logging Tool

<#
.SYNOPSIS
Comprehensive Logging Tool

.DESCRIPTION
This script provides functionality for creating, managing, and analyzing log files
in various formats. It includes features for creating logs, appending to existing logs,
searching logs, and performing basic log analysis.

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

.EXAMPLE
.\LoggingTool.ps1
#>

# Global variables
$global:logPath = "$env:USERPROFILE\Desktop\Logs"
$global:currentLogFile = ""

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Comprehensive Logging Tool ===" -ForegroundColor Cyan
    Write-Host "Current Log File: $global:currentLogFile"
    Write-Host "1. Create New Log File"
    Write-Host "2. Append to Existing Log"
    Write-Host "3. View Log Content"
    Write-Host "4. Search Log"
    Write-Host "5. Analyze Log (Basic Statistics)"
    Write-Host "6. Export Log to CSV"
    Write-Host "7. Rotate Log File"
    Write-Host "8. Delete Log File"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Creates a new log file.
#>
function Create-NewLogFile {
    $logName = Read-Host "Enter the name for the new log file (without extension)"
    $logFormat = Read-Host "Enter log format (txt/json/xml)"
    
    $fileName = "$logName.$(Get-Date -Format 'yyyyMMdd').$logFormat"
    $global:currentLogFile = Join-Path $global:logPath $fileName

    if (!(Test-Path $global:logPath)) {
        New-Item -ItemType Directory -Path $global:logPath | Out-Null
    }

    switch ($logFormat) {
        "txt" { "" | Out-File -FilePath $global:currentLogFile }
        "json" { "[]" | Out-File -FilePath $global:currentLogFile }
        "xml" { '<?xml version="1.0" encoding="UTF-8"?><log></log>' | Out-File -FilePath $global:currentLogFile }
        default { Write-Host "Invalid format. Creating a txt file." -ForegroundColor Yellow; "" | Out-File -FilePath $global:currentLogFile }
    }

    Write-Host "Log file created: $global:currentLogFile" -ForegroundColor Green
}

<#
.SYNOPSIS
Appends an entry to the current log file.
#>
function Append-ToLog {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    $logEntry = Read-Host "Enter the log entry"
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

    $fileExtension = [System.IO.Path]::GetExtension($global:currentLogFile)
    switch ($fileExtension) {
        ".txt" { 
            "$timestamp - $logEntry" | Out-File -FilePath $global:currentLogFile -Append 
        }
        ".json" { 
            $jsonContent = Get-Content -Raw -Path $global:currentLogFile | ConvertFrom-Json
            $newEntry = @{
                "timestamp" = $timestamp
                "message" = $logEntry
            }
            $jsonContent += $newEntry
            $jsonContent | ConvertTo-Json | Set-Content -Path $global:currentLogFile
        }
        ".xml" { 
            [xml]$xmlContent = Get-Content -Path $global:currentLogFile
            $newEntry = $xmlContent.CreateElement("entry")
            $newEntry.SetAttribute("timestamp", $timestamp)
            $newEntry.InnerText = $logEntry
            $xmlContent.log.AppendChild($newEntry) | Out-Null
            $xmlContent.Save($global:currentLogFile)
        }
    }

    Write-Host "Log entry added successfully." -ForegroundColor Green
}

<#
.SYNOPSIS
Views the content of the current log file.
#>
function View-LogContent {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    Get-Content -Path $global:currentLogFile | Out-Host
    Read-Host "Press Enter to continue..."
}

<#
.SYNOPSIS
Searches the current log file for a specific term.
#>
function Search-Log {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    $searchTerm = Read-Host "Enter the search term"
    $results = Get-Content -Path $global:currentLogFile | Select-String -Pattern $searchTerm

    if ($results) {
        Write-Host "Search Results:" -ForegroundColor Yellow
        $results | ForEach-Object { Write-Host $_ }
    } else {
        Write-Host "No matches found." -ForegroundColor Yellow
    }

    Read-Host "Press Enter to continue..."
}

<#
.SYNOPSIS
Performs basic analysis on the current log file.
#>
function Analyze-Log {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    $content = Get-Content -Path $global:currentLogFile
    $totalEntries = $content.Count
    $uniqueEntries = ($content | Select-Object -Unique).Count
    $firstEntry = $content | Select-Object -First 1
    $lastEntry = $content | Select-Object -Last 1

    Write-Host "Log Analysis:" -ForegroundColor Yellow
    Write-Host "Total Entries: $totalEntries"
    Write-Host "Unique Entries: $uniqueEntries"
    Write-Host "First Entry: $firstEntry"
    Write-Host "Last Entry: $lastEntry"

    Read-Host "Press Enter to continue..."
}

<#
.SYNOPSIS
Exports the current log file to CSV format.
#>
function Export-LogToCSV {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    $csvPath = [System.IO.Path]::ChangeExtension($global:currentLogFile, "csv")
    $content = Get-Content -Path $global:currentLogFile

    $csvData = $content | ForEach-Object {
        if ($_ -match "^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (.*)$") {
            [PSCustomObject]@{
                Timestamp = $matches[1]
                Message = $matches[2]
            }
        }
    }

    $csvData | Export-Csv -Path $csvPath -NoTypeInformation
    Write-Host "Log exported to CSV: $csvPath" -ForegroundColor Green
}

<#
.SYNOPSIS
Rotates the current log file.
#>
function Rotate-LogFile {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    $directory = [System.IO.Path]::GetDirectoryName($global:currentLogFile)
    $fileName = [System.IO.Path]::GetFileNameWithoutExtension($global:currentLogFile)
    $extension = [System.IO.Path]::GetExtension($global:currentLogFile)

    $newFileName = "{0}_{1}{2}" -f $fileName, (Get-Date -Format "yyyyMMddHHmmss"), $extension
    $newFilePath = Join-Path $directory $newFileName

    Move-Item -Path $global:currentLogFile -Destination $newFilePath
    Write-Host "Log file rotated. New file: $newFilePath" -ForegroundColor Green

    # Create a new empty log file
    "" | Out-File -FilePath $global:currentLogFile
    Write-Host "New empty log file created: $global:currentLogFile" -ForegroundColor Green
}

<#
.SYNOPSIS
Deletes the current log file.
#>
function Delete-LogFile {
    if ([string]::IsNullOrEmpty($global:currentLogFile)) {
        Write-Host "No log file selected. Please create or select a log file first." -ForegroundColor Red
        return
    }

    $confirmation = Read-Host "Are you sure you want to delete the current log file? (Y/N)"
    if ($confirmation -eq "Y") {
        Remove-Item -Path $global:currentLogFile -Force
        Write-Host "Log file deleted: $global:currentLogFile" -ForegroundColor Green
        $global:currentLogFile = ""
    } else {
        Write-Host "Deletion cancelled." -ForegroundColor Yellow
    }
}

# Main program loop
do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-9)"

    switch ($choice) {
        "1" { Create-NewLogFile }
        "2" { Append-ToLog }
        "3" { View-LogContent }
        "4" { Search-Log }
        "5" { Analyze-Log }
        "6" { Export-LogToCSV }
        "7" { Rotate-LogFile }
        "8" { Delete-LogFile }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Comprehensive Logging Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to manage and analyze log files:
    • Creating new log files in various formats (txt, json, xml)
    • Appending entries to existing logs
    • Viewing log content
    • Searching logs for specific terms
    • Performing basic log analysis
    • Exporting logs to CSV format
    • Rotating log files
    • Deleting log files
  3. Support for different log formats (txt, json, xml)
  4. Error handling and user confirmations for critical operations

Key features:

  • Flexible log creation in multiple formats
  • Easy log entry addition with automatic timestamps
  • Search functionality for quick information retrieval
  • Basic log analysis for insights
  • Log rotation for managing file sizes
  • CSV export for further analysis in spreadsheet applications
  • Safe log file deletion with user confirmation

This tool is particularly useful for:

  • Developers needing to implement logging in their applications
  • System administrators managing log files
  • IT professionals troubleshooting issues using logs
  • Anyone needing to create, manage, or analyze log files

To use this script effectively:

  1. Run PowerShell with appropriate permissions to create and modify files in the specified log directory
  2. Ensure you have write access to the desktop or modify the $global:logPath variable to a suitable location
  3. Be cautious when deleting log files, as this operation is irreversible

This script provides a comprehensive set of features for log management and analysis, making it easier to maintain, search, and gain insights from log files in various formats.

Certificates Analyzer Tool

<#
.SYNOPSIS
Certificates Analyzer Tool

.DESCRIPTION
This script analyzes and audits certificates on a Windows system, including those in the
certificate store and those used by IIS. It provides insights into certificate expiration,
usage, and potential issues.

.NOTES
File Name      : CertificatesAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights, and IIS if analyzing IIS certificates
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\CertificatesAnalyzer.ps1
#>

# Import required modules
Import-Module WebAdministration -ErrorAction SilentlyContinue

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Certificates Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze All Certificates in Local Machine Store"
    Write-Host "2. Check for Expiring Certificates"
    Write-Host "3. Analyze IIS Binding Certificates"
    Write-Host "4. Check for Weak Key Certificates"
    Write-Host "5. Analyze Certificate Chain"
    Write-Host "6. Check for Duplicate Certificates"
    Write-Host "7. Analyze Certificate Usage"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Analyzes all certificates in the Local Machine store.

.OUTPUTS
Array of PSObjects containing certificate details.
#>
function Analyze-AllCertificates {
    Write-Host "`nAnalyzing All Certificates in Local Machine Store..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object { $_.PSIsContainer -eq $false }
    $results = @()
    foreach ($cert in $certs) {
        $results += [PSCustomObject]@{
            Subject = $cert.Subject
            Issuer = $cert.Issuer
            Thumbprint = $cert.Thumbprint
            NotBefore = $cert.NotBefore
            NotAfter = $cert.NotAfter
            Store = $cert.PSParentPath.Split('\')[-1]
            HasPrivateKey = $cert.HasPrivateKey
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks for expiring certificates.

.OUTPUTS
Array of PSObjects containing expiring certificate details.
#>
function Check-ExpiringCertificates {
    Write-Host "`nChecking for Expiring Certificates..." -ForegroundColor Yellow
    $expirationThreshold = (Get-Date).AddDays(30)
    $certs = Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object { $_.PSIsContainer -eq $false -and $_.NotAfter -le $expirationThreshold }
    $results = @()
    foreach ($cert in $certs) {
        $results += [PSCustomObject]@{
            Subject = $cert.Subject
            Thumbprint = $cert.Thumbprint
            ExpirationDate = $cert.NotAfter
            DaysUntilExpiration = ($cert.NotAfter - (Get-Date)).Days
            Store = $cert.PSParentPath.Split('\')[-1]
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes IIS binding certificates.

.OUTPUTS
Array of PSObjects containing IIS binding certificate details.
#>
function Analyze-IISBindingCertificates {
    Write-Host "`nAnalyzing IIS Binding Certificates..." -ForegroundColor Yellow
    $results = @()
    if (Get-Module -ListAvailable -Name WebAdministration) {
        $websites = Get-Website
        foreach ($site in $websites) {
            $bindings = $site.Bindings.Collection | Where-Object { $_.Protocol -eq "https" }
            foreach ($binding in $bindings) {
                $cert = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.Thumbprint -eq $binding.CertificateHash }
                if ($cert) {
                    $results += [PSCustomObject]@{
                        Website = $site.Name
                        Binding = $binding.BindingInformation
                        CertSubject = $cert.Subject
                        Thumbprint = $cert.Thumbprint
                        ExpirationDate = $cert.NotAfter
                        DaysUntilExpiration = ($cert.NotAfter - (Get-Date)).Days
                    }
                }
            }
        }
    } else {
        Write-Host "WebAdministration module not available. Unable to analyze IIS bindings." -ForegroundColor Red
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks for certificates with weak keys.

.OUTPUTS
Array of PSObjects containing weak key certificate details.
#>
function Check-WeakKeyCertificates {
    Write-Host "`nChecking for Weak Key Certificates..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object { $_.PSIsContainer -eq $false }
    $results = @()
    foreach ($cert in $certs) {
        if ($cert.PublicKey.Key.KeySize -lt 2048) {
            $results += [PSCustomObject]@{
                Subject = $cert.Subject
                Thumbprint = $cert.Thumbprint
                KeySize = $cert.PublicKey.Key.KeySize
                Store = $cert.PSParentPath.Split('\')[-1]
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes certificate chains.

.OUTPUTS
Array of PSObjects containing certificate chain details.
#>
function Analyze-CertificateChain {
    Write-Host "`nAnalyzing Certificate Chain..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object { $_.PSIsContainer -eq $false }
    $results = @()
    foreach ($cert in $certs) {
        $chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain
        $chain.Build($cert) | Out-Null
        $chainStatus = $chain.ChainStatus | ForEach-Object { $_.Status }
        $results += [PSCustomObject]@{
            Subject = $cert.Subject
            Thumbprint = $cert.Thumbprint
            ChainValid = $chain.ChainStatus.Length -eq 0
            ChainStatus = if ($chainStatus) { $chainStatus -join ", " } else { "Valid" }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks for duplicate certificates.

.OUTPUTS
Array of PSObjects containing duplicate certificate details.
#>
function Check-DuplicateCertificates {
    Write-Host "`nChecking for Duplicate Certificates..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object { $_.PSIsContainer -eq $false }
    $duplicates = $certs | Group-Object -Property Thumbprint | Where-Object { $_.Count -gt 1 }
    $results = @()
    foreach ($duplicate in $duplicates) {
        foreach ($cert in $duplicate.Group) {
            $results += [PSCustomObject]@{
                Subject = $cert.Subject
                Thumbprint = $cert.Thumbprint
                Store = $cert.PSParentPath.Split('\')[-1]
                NotAfter = $cert.NotAfter
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes certificate usage.

.OUTPUTS
Array of PSObjects containing certificate usage details.
#>
function Analyze-CertificateUsage {
    Write-Host "`nAnalyzing Certificate Usage..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object { $_.PSIsContainer -eq $false }
    $results = @()
    foreach ($cert in $certs) {
        $enhancedKeyUsage = $cert.EnhancedKeyUsageList | ForEach-Object { $_.FriendlyName }
        $results += [PSCustomObject]@{
            Subject = $cert.Subject
            Thumbprint = $cert.Thumbprint
            KeyUsage = $cert.KeyUsages -join ", "
            EnhancedKeyUsage = if ($enhancedKeyUsage) { $enhancedKeyUsage -join ", " } else { "Not specified" }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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>Certificates 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>Certificates Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>All Certificates</h2>
    $($AllResults.AllCertificates | ConvertTo-Html -Fragment)

    <h2>Expiring Certificates</h2>
    $($AllResults.ExpiringCertificates | ConvertTo-Html -Fragment)

    <h2>IIS Binding Certificates</h2>
    $($AllResults.IISBindingCertificates | ConvertTo-Html -Fragment)

    <h2>Weak Key Certificates</h2>
    $($AllResults.WeakKeyCertificates | ConvertTo-Html -Fragment)

    <h2>Certificate Chain Analysis</h2>
    $($AllResults.CertificateChain | ConvertTo-Html -Fragment)

    <h2>Duplicate Certificates</h2>
    $($AllResults.DuplicateCertificates | ConvertTo-Html -Fragment)

    <h2>Certificate Usage</h2>
    $($AllResults.CertificateUsage | 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-9)"

    switch ($choice) {
        "1" { $allResults.AllCertificates = Analyze-AllCertificates }
        "2" { $allResults.ExpiringCertificates = Check-ExpiringCertificates }
        "3" { $allResults.IISBindingCertificates = Analyze-IISBindingCertificates }
        "4" { $allResults.WeakKeyCertificates = Check-WeakKeyCertificates }
        "5" { $allResults.CertificateChain = Analyze-CertificateChain }
        "6" { $allResults.DuplicateCertificates = Check-DuplicateCertificates }
        "7" { $allResults.CertificateUsage = Analyze-CertificateUsage }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Certificates Analyzer Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of certificates:
    • Analysis of all certificates in the Local Machine store
    • Check for expiring certificates
    • Analysis of IIS binding certificates
    • Check for weak key certificates
    • Analysis of certificate chains
    • Check for duplicate certificates
    • Analysis of certificate usage
  3. Comprehensive error handling for each analysis function.
  4. A function to generate an HTML report of all collected data.

Key features:

  • Detailed analysis of all certificates in the Local Machine store
  • Identification of certificates nearing expiration
  • Review of certificates used in IIS bindings
  • Detection of certificates with weak keys
  • Analysis of certificate chains for validity
  • Identification of duplicate certificates across stores
  • Examination of certificate usage and purposes
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • System administrators managing certificates
  • Security professionals auditing certificate deployments
  • IT professionals troubleshooting certificate-related issues
  • DevOps engineers managing SSL/TLS certificates

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to access certificate stores
  3. Have the WebAdministration module available if you want to analyze IIS certificates

This script provides a comprehensive overview of certificates on a Windows system, making it easier to audit and maintain certificate deployments, identify potential issues, and ensure the security of SSL/TLS implementations.

IIS (Internet Information Services) Analyzer Tool

<#
.SYNOPSIS
IIS (Internet Information Services) Analyzer Tool

.DESCRIPTION
This script analyzes and audits IIS configurations, including websites, application pools,
bindings, SSL certificates, and other related settings on Windows Servers.

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

.EXAMPLE
.\IISAnalyzer.ps1
#>

# Check if WebAdministration module is available
if (-not (Get-Module -ListAvailable -Name WebAdministration)) {
    Write-Host "WebAdministration module not found. Please ensure IIS is installed with management tools." -ForegroundColor Red
    exit
}

# Import required module
Import-Module WebAdministration

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== IIS Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze Websites"
    Write-Host "2. Review Application Pools"
    Write-Host "3. Analyze Bindings and SSL Certificates"
    Write-Host "4. Check Virtual Directories"
    Write-Host "5. Review HTTP Response Headers"
    Write-Host "6. Analyze Authentication Settings"
    Write-Host "7. Check Logging Configuration"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Analyzes IIS Websites.

.OUTPUTS
Array of PSObjects containing Website details.
#>
function Analyze-Websites {
    Write-Host "`nAnalyzing Websites..." -ForegroundColor Yellow
    $websites = Get-Website
    $results = @()
    foreach ($site in $websites) {
        $results += [PSCustomObject]@{
            Name = $site.Name
            ID = $site.ID
            State = $site.State
            PhysicalPath = $site.PhysicalPath
            ApplicationPool = $site.ApplicationPool
            Bindings = ($site.Bindings.Collection | ForEach-Object { "$($_.Protocol)/$($_.BindingInformation)" }) -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews Application Pools.

.OUTPUTS
Array of PSObjects containing Application Pool details.
#>
function Review-ApplicationPools {
    Write-Host "`nReviewing Application Pools..." -ForegroundColor Yellow
    $appPools = Get-IISAppPool
    $results = @()
    foreach ($pool in $appPools) {
        $results += [PSCustomObject]@{
            Name = $pool.Name
            State = $pool.State
            ManagedRuntimeVersion = $pool.ManagedRuntimeVersion
            ManagedPipelineMode = $pool.ManagedPipelineMode
            StartMode = $pool.StartMode
            IdentityType = $pool.ProcessModel.IdentityType
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Bindings and SSL Certificates.

.OUTPUTS
Array of PSObjects containing Binding and SSL Certificate details.
#>
function Analyze-BindingsAndSSL {
    Write-Host "`nAnalyzing Bindings and SSL Certificates..." -ForegroundColor Yellow
    $websites = Get-Website
    $results = @()
    foreach ($site in $websites) {
        foreach ($binding in $site.Bindings.Collection) {
            $cert = $null
            if ($binding.Protocol -eq "https") {
                $cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object {$_.Thumbprint -eq $binding.CertificateHash}
            }
            $results += [PSCustomObject]@{
                Website = $site.Name
                Protocol = $binding.Protocol
                BindingInfo = $binding.BindingInformation
                SSLThumbprint = if ($cert) { $cert.Thumbprint } else { "N/A" }
                SSLExpirationDate = if ($cert) { $cert.NotAfter } else { "N/A" }
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Virtual Directories.

.OUTPUTS
Array of PSObjects containing Virtual Directory details.
#>
function Check-VirtualDirectories {
    Write-Host "`nChecking Virtual Directories..." -ForegroundColor Yellow
    $vdirs = Get-WebVirtualDirectory
    $results = @()
    foreach ($vdir in $vdirs) {
        $results += [PSCustomObject]@{
            Name = $vdir.Name
            PhysicalPath = $vdir.PhysicalPath
            Application = $vdir.Application
            Website = $vdir.Website
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews HTTP Response Headers.

.OUTPUTS
Array of PSObjects containing HTTP Response Header details.
#>
function Review-HTTPResponseHeaders {
    Write-Host "`nReviewing HTTP Response Headers..." -ForegroundColor Yellow
    $websites = Get-Website
    $results = @()
    foreach ($site in $websites) {
        $headers = Get-WebConfigurationProperty -Filter "system.webServer/httpProtocol/customHeaders" -PSPath "IIS:\Sites\$($site.Name)" -Name "."
        foreach ($header in $headers.Collection) {
            $results += [PSCustomObject]@{
                Website = $site.Name
                HeaderName = $header.Name
                HeaderValue = $header.Value
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Authentication Settings.

.OUTPUTS
Array of PSObjects containing Authentication Setting details.
#>
function Analyze-AuthenticationSettings {
    Write-Host "`nAnalyzing Authentication Settings..." -ForegroundColor Yellow
    $websites = Get-Website
    $results = @()
    foreach ($site in $websites) {
        $authTypes = @("Anonymous", "Basic", "Windows", "Digest")
        $authSettings = @{}
        foreach ($authType in $authTypes) {
            $authSettings[$authType] = (Get-WebConfigurationProperty -Filter "system.webServer/security/authentication/$authType`Authentication" -PSPath "IIS:\Sites\$($site.Name)" -Name "enabled").Value
        }
        $results += [PSCustomObject]@{
            Website = $site.Name
            AnonymousAuth = $authSettings["Anonymous"]
            BasicAuth = $authSettings["Basic"]
            WindowsAuth = $authSettings["Windows"]
            DigestAuth = $authSettings["Digest"]
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Logging Configuration.

.OUTPUTS
Array of PSObjects containing Logging Configuration details.
#>
function Check-LoggingConfiguration {
    Write-Host "`nChecking Logging Configuration..." -ForegroundColor Yellow
    $websites = Get-Website
    $results = @()
    foreach ($site in $websites) {
        $logFile = Get-WebConfigurationProperty -Filter "system.applicationHost/sites/site[@name='$($site.Name)']/logFile" -PSPath "MACHINE/WEBROOT/APPHOST" -Name "."
        $results += [PSCustomObject]@{
            Website = $site.Name
            LogFormat = $logFile.logFormat
            Directory = $logFile.directory
            Enabled = $logFile.enabled
            Period = $logFile.period
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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>IIS 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>IIS Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

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

    <h2>Application Pools</h2>
    $($AllResults.ApplicationPools | ConvertTo-Html -Fragment)

    <h2>Bindings and SSL Certificates</h2>
    $($AllResults.BindingsAndSSL | ConvertTo-Html -Fragment)

    <h2>Virtual Directories</h2>
    $($AllResults.VirtualDirectories | ConvertTo-Html -Fragment)

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

    <h2>Authentication Settings</h2>
    $($AllResults.AuthenticationSettings | ConvertTo-Html -Fragment)

    <h2>Logging Configuration</h2>
    $($AllResults.LoggingConfiguration | 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-9)"

    switch ($choice) {
        "1" { $allResults.Websites = Analyze-Websites }
        "2" { $allResults.ApplicationPools = Review-ApplicationPools }
        "3" { $allResults.BindingsAndSSL = Analyze-BindingsAndSSL }
        "4" { $allResults.VirtualDirectories = Check-VirtualDirectories }
        "5" { $allResults.HTTPResponseHeaders = Review-HTTPResponseHeaders }
        "6" { $allResults.AuthenticationSettings = Analyze-AuthenticationSettings }
        "7" { $allResults.LoggingConfiguration = Check-LoggingConfiguration }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This IIS Analyzer Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of IIS:
    • Website analysis
    • Application Pool review
    • Bindings and SSL Certificate analysis
    • Virtual Directory check
    • HTTP Response Header review
    • Authentication Settings analysis
    • Logging Configuration check
  3. Comprehensive error handling for each analysis function.
  4. A function to generate an HTML report of all collected data.

Key features:

  • Detailed analysis of IIS Websites and their configurations
  • Review of Application Pools and their settings
  • Analysis of Bindings and SSL Certificates, including expiration dates
  • Examination of Virtual Directories
  • Overview of custom HTTP Response Headers
  • Analysis of Authentication Settings for each website
  • Review of Logging Configurations
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • IIS Administrators managing web servers
  • System administrators overseeing IIS configurations
  • Security professionals auditing web server settings
  • DevOps engineers managing IIS deployments

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure IIS is installed with the management tools (which includes the WebAdministration module)
  3. Have the necessary permissions to query IIS configurations

This script provides a comprehensive overview of IIS configurations on a Windows Server, making it easier to audit and maintain IIS settings, websites, and application pools. It can significantly streamline the process of managing and documenting IIS configurations in enterprise environments.

File Server Resource Manager (FSRM) Analyzer Tool

<#
.SYNOPSIS
File Server Resource Manager (FSRM) Analyzer Tool

.DESCRIPTION
This script analyzes and audits File Server Resource Manager configurations, including
quotas, file screens, file groups, and classification rules on Windows Servers.

.NOTES
File Name      : FSRMAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, FSRM feature installed, and appropriate permissions
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\FSRMAnalyzer.ps1
#>

# Check if FSRM module is available
if (-not (Get-Module -ListAvailable -Name FileServerResourceManager)) {
    Write-Host "File Server Resource Manager module not found. Please ensure FSRM is installed." -ForegroundColor Red
    exit
}

# Import required module
Import-Module FileServerResourceManager

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== File Server Resource Manager Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze Quota Templates"
    Write-Host "2. Review File Screen Templates"
    Write-Host "3. Analyze File Groups"
    Write-Host "4. Review Classification Rules"
    Write-Host "5. Check File Management Tasks"
    Write-Host "6. Analyze Storage Reports"
    Write-Host "7. Review FSRM Settings"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Analyzes Quota Templates.

.OUTPUTS
Array of PSObjects containing Quota Template details.
#>
function Analyze-QuotaTemplates {
    Write-Host "`nAnalyzing Quota Templates..." -ForegroundColor Yellow
    $quotaTemplates = Get-FsrmQuotaTemplate
    $results = @()
    foreach ($template in $quotaTemplates) {
        $results += [PSCustomObject]@{
            Name = $template.Name
            Size = $template.Size
            SoftLimit = $template.SoftLimit
            ThresholdPercentages = $template.Threshold -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews File Screen Templates.

.OUTPUTS
Array of PSObjects containing File Screen Template details.
#>
function Review-FileScreenTemplates {
    Write-Host "`nReviewing File Screen Templates..." -ForegroundColor Yellow
    $screenTemplates = Get-FsrmFileScreenTemplate
    $results = @()
    foreach ($template in $screenTemplates) {
        $results += [PSCustomObject]@{
            Name = $template.Name
            IncludeGroup = $template.IncludeGroup -join ", "
            Active = $template.Active
            Description = $template.Description
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes File Groups.

.OUTPUTS
Array of PSObjects containing File Group details.
#>
function Analyze-FileGroups {
    Write-Host "`nAnalyzing File Groups..." -ForegroundColor Yellow
    $fileGroups = Get-FsrmFileGroup
    $results = @()
    foreach ($group in $fileGroups) {
        $results += [PSCustomObject]@{
            Name = $group.Name
            IncludePattern = $group.IncludePattern -join ", "
            ExcludePattern = $group.ExcludePattern -join ", "
            Description = $group.Description
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews Classification Rules.

.OUTPUTS
Array of PSObjects containing Classification Rule details.
#>
function Review-ClassificationRules {
    Write-Host "`nReviewing Classification Rules..." -ForegroundColor Yellow
    $classRules = Get-FsrmClassificationRule
    $results = @()
    foreach ($rule in $classRules) {
        $results += [PSCustomObject]@{
            Name = $rule.Name
            Property = $rule.Property
            PropertyValue = $rule.PropertyValue
            Description = $rule.Description
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks File Management Tasks.

.OUTPUTS
Array of PSObjects containing File Management Task details.
#>
function Check-FileManagementTasks {
    Write-Host "`nChecking File Management Tasks..." -ForegroundColor Yellow
    $fmTasks = Get-FsrmFileManagementJob
    $results = @()
    foreach ($task in $fmTasks) {
        $results += [PSCustomObject]@{
            Name = $task.Name
            Namespace = $task.Namespace
            Action = $task.Action
            Enabled = $task.Enabled
            Schedule = $task.Schedule
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Storage Reports.

.OUTPUTS
Array of PSObjects containing Storage Report details.
#>
function Analyze-StorageReports {
    Write-Host "`nAnalyzing Storage Reports..." -ForegroundColor Yellow
    $reports = Get-FsrmStorageReport
    $results = @()
    foreach ($report in $reports) {
        $results += [PSCustomObject]@{
            Name = $report.Name
            NameSpace = $report.NameSpace
            ReportFormats = $report.ReportFormats -join ", "
            Schedule = $report.Schedule
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews FSRM Settings.

.OUTPUTS
PSObject containing FSRM Settings.
#>
function Review-FSRMSettings {
    Write-Host "`nReviewing FSRM Settings..." -ForegroundColor Yellow
    $settings = Get-FsrmSetting
    $results = [PSCustomObject]@{
        SmtpServer = $settings.SmtpServer
        AdminEmailAddress = $settings.AdminEmailAddress
        FromEmailAddress = $settings.FromEmailAddress
        CommandNotificationLimit = $settings.CommandNotificationLimit
        EmailNotificationLimit = $settings.EmailNotificationLimit
        EventNotificationLimit = $settings.EventNotificationLimit
    }
    $results | Format-List
    return $results
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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>FSRM Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>File Server Resource Manager Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>Quota Templates</h2>
    $($AllResults.QuotaTemplates | ConvertTo-Html -Fragment)

    <h2>File Screen Templates</h2>
    $($AllResults.FileScreenTemplates | ConvertTo-Html -Fragment)

    <h2>File Groups</h2>
    $($AllResults.FileGroups | ConvertTo-Html -Fragment)

    <h2>Classification Rules</h2>
    $($AllResults.ClassificationRules | ConvertTo-Html -Fragment)

    <h2>File Management Tasks</h2>
    $($AllResults.FileManagementTasks | ConvertTo-Html -Fragment)

    <h2>Storage Reports</h2>
    $($AllResults.StorageReports | ConvertTo-Html -Fragment)

    <h2>FSRM Settings</h2>
    $($AllResults.FSRMSettings | 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-9)"

    switch ($choice) {
        "1" { $allResults.QuotaTemplates = Analyze-QuotaTemplates }
        "2" { $allResults.FileScreenTemplates = Review-FileScreenTemplates }
        "3" { $allResults.FileGroups = Analyze-FileGroups }
        "4" { $allResults.ClassificationRules = Review-ClassificationRules }
        "5" { $allResults.FileManagementTasks = Check-FileManagementTasks }
        "6" { $allResults.StorageReports = Analyze-StorageReports }
        "7" { $allResults.FSRMSettings = Review-FSRMSettings }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This File Server Resource Manager (FSRM) Analyzer Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of FSRM:
    • Quota Templates analysis
    • File Screen Templates review
    • File Groups analysis
    • Classification Rules review
    • File Management Tasks check
    • Storage Reports analysis
    • FSRM Settings review
  3. Comprehensive error handling for each analysis function.
  4. A function to generate an HTML report of all collected data.

Key features:

  • Detailed analysis of Quota Templates and their thresholds
  • Review of File Screen Templates and their included file groups
  • Analysis of File Groups and their patterns
  • Examination of Classification Rules
  • Overview of File Management Tasks and their schedules
  • Analysis of configured Storage Reports
  • Review of general FSRM settings like email configurations
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • System administrators managing file servers
  • Storage administrators overseeing quota and file screening policies
  • IT auditors reviewing file server configurations
  • Compliance officers ensuring adherence to file management policies

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure the File Server Resource Manager feature is installed on the server
  3. Have the necessary permissions to query FSRM configurations

This script provides a comprehensive overview of File Server Resource Manager configurations on a Windows Server, making it easier to audit and maintain FSRM policies, quotas, and file screening rules. It can significantly streamline the process of managing and documenting FSRM configurations in enterprise environments.

Group Policy Analyzer Tool

<#
.SYNOPSIS
Group Policy Analyzer Tool

.DESCRIPTION
This script analyzes and audits Group Policy Objects (GPOs) in an Active Directory environment,
providing detailed information about policy settings, links, and potential issues.

.NOTES
File Name      : GroupPolicyAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, GroupPolicy module, and appropriate AD permissions
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\GroupPolicyAnalyzer.ps1
#>

# Import required modules
Import-Module GroupPolicy
Import-Module ActiveDirectory

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Group Policy Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze All GPOs"
    Write-Host "2. Find Unlinked GPOs"
    Write-Host "3. Identify GPOs with No Settings"
    Write-Host "4. Check for Conflicting GPO Settings"
    Write-Host "5. Analyze GPO Links"
    Write-Host "6. Review GPO Permissions"
    Write-Host "7. Check GPO Version Numbers"
    Write-Host "8. Analyze GPO WMI Filters"
    Write-Host "9. Generate Comprehensive HTML Report"
    Write-Host "10. Exit"
}

<#
.SYNOPSIS
Analyzes all GPOs in the domain.

.OUTPUTS
Array of PSObjects containing GPO details.
#>
function Analyze-AllGPOs {
    Write-Host "`nAnalyzing All GPOs..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $results = @()
    foreach ($gpo in $gpos) {
        $report = Get-GPOReport -Guid $gpo.Id -ReportType XML
        $settingsCount = ([xml]$report).GPO.Computer.ExtensionData.Extension.Policy.Count + 
                         ([xml]$report).GPO.User.ExtensionData.Extension.Policy.Count
        $results += [PSCustomObject]@{
            Name = $gpo.DisplayName
            ID = $gpo.Id
            CreationTime = $gpo.CreationTime
            ModificationTime = $gpo.ModificationTime
            SettingsCount = $settingsCount
            Status = $gpo.GpoStatus
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Finds unlinked GPOs in the domain.

.OUTPUTS
Array of PSObjects containing unlinked GPO details.
#>
function Find-UnlinkedGPOs {
    Write-Host "`nFinding Unlinked GPOs..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $unlinkedGPOs = @()
    foreach ($gpo in $gpos) {
        $linkedOUs = Get-ADOrganizationalUnit -Filter * | Where-Object {(Get-GPInheritance -Target $_.DistinguishedName).GpoLinks.DisplayName -contains $gpo.DisplayName}
        if ($linkedOUs.Count -eq 0) {
            $unlinkedGPOs += [PSCustomObject]@{
                Name = $gpo.DisplayName
                ID = $gpo.Id
                CreationTime = $gpo.CreationTime
            }
        }
    }
    $unlinkedGPOs | Format-Table -AutoSize
    return $unlinkedGPOs
}

<#
.SYNOPSIS
Identifies GPOs with no settings configured.

.OUTPUTS
Array of PSObjects containing empty GPO details.
#>
function Identify-EmptyGPOs {
    Write-Host "`nIdentifying GPOs with No Settings..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $emptyGPOs = @()
    foreach ($gpo in $gpos) {
        $report = Get-GPOReport -Guid $gpo.Id -ReportType XML
        $settingsCount = ([xml]$report).GPO.Computer.ExtensionData.Extension.Policy.Count + 
                         ([xml]$report).GPO.User.ExtensionData.Extension.Policy.Count
        if ($settingsCount -eq 0) {
            $emptyGPOs += [PSCustomObject]@{
                Name = $gpo.DisplayName
                ID = $gpo.Id
                CreationTime = $gpo.CreationTime
            }
        }
    }
    $emptyGPOs | Format-Table -AutoSize
    return $emptyGPOs
}

<#
.SYNOPSIS
Checks for potentially conflicting GPO settings.

.OUTPUTS
Array of PSObjects containing conflicting GPO details.
#>
function Check-ConflictingGPOSettings {
    Write-Host "`nChecking for Conflicting GPO Settings..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $conflictingSettings = @()
    $allSettings = @{}

    foreach ($gpo in $gpos) {
        $report = ([xml](Get-GPOReport -Guid $gpo.Id -ReportType XML))
        $settings = $report.GPO.Computer.ExtensionData.Extension.Policy + $report.GPO.User.ExtensionData.Extension.Policy
        
        foreach ($setting in $settings) {
            $key = "$($setting.Name):$($setting.Class)"
            if ($allSettings.ContainsKey($key)) {
                $conflictingSettings += [PSCustomObject]@{
                    SettingName = $setting.Name
                    GPO1 = $allSettings[$key]
                    GPO2 = $gpo.DisplayName
                }
            } else {
                $allSettings[$key] = $gpo.DisplayName
            }
        }
    }
    $conflictingSettings | Format-Table -AutoSize
    return $conflictingSettings
}

<#
.SYNOPSIS
Analyzes GPO links across the domain.

.OUTPUTS
Array of PSObjects containing GPO link details.
#>
function Analyze-GPOLinks {
    Write-Host "`nAnalyzing GPO Links..." -ForegroundColor Yellow
    $domain = Get-ADDomain
    $ous = Get-ADOrganizationalUnit -Filter *
    $gpoLinks = @()

    foreach ($ou in $ous) {
        $links = (Get-GPInheritance -Target $ou.DistinguishedName).GpoLinks
        foreach ($link in $links) {
            $gpoLinks += [PSCustomObject]@{
                GPOName = $link.DisplayName
                LinkedOU = $ou.Name
                Enabled = $link.Enabled
                Enforced = $link.Enforced
                Order = $link.Order
            }
        }
    }
    $gpoLinks | Format-Table -AutoSize
    return $gpoLinks
}

<#
.SYNOPSIS
Reviews GPO permissions.

.OUTPUTS
Array of PSObjects containing GPO permission details.
#>
function Review-GPOPermissions {
    Write-Host "`nReviewing GPO Permissions..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $gpoPermissions = @()

    foreach ($gpo in $gpos) {
        $permissions = Get-GPPermission -Guid $gpo.Id -All
        foreach ($perm in $permissions) {
            $gpoPermissions += [PSCustomObject]@{
                GPOName = $gpo.DisplayName
                Trustee = $perm.Trustee.Name
                Permission = $perm.Permission
            }
        }
    }
    $gpoPermissions | Format-Table -AutoSize
    return $gpoPermissions
}

<#
.SYNOPSIS
Checks GPO version numbers.

.OUTPUTS
Array of PSObjects containing GPO version details.
#>
function Check-GPOVersions {
    Write-Host "`nChecking GPO Version Numbers..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $gpoVersions = @()

    foreach ($gpo in $gpos) {
        $gpoVersions += [PSCustomObject]@{
            Name = $gpo.DisplayName
            ComputerVersion = $gpo.Computer.DSVersion
            UserVersion = $gpo.User.DSVersion
        }
    }
    $gpoVersions | Format-Table -AutoSize
    return $gpoVersions
}

<#
.SYNOPSIS
Analyzes GPO WMI Filters.

.OUTPUTS
Array of PSObjects containing GPO WMI Filter details.
#>
function Analyze-GPOWMIFilters {
    Write-Host "`nAnalyzing GPO WMI Filters..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $wmiFilters = @()

    foreach ($gpo in $gpos) {
        $filter = $gpo.WmiFilter
        if ($filter) {
            $wmiFilters += [PSCustomObject]@{
                GPOName = $gpo.DisplayName
                WMIFilterName = $filter.Name
                WMIFilterDescription = $filter.Description
            }
        }
    }
    $wmiFilters | Format-Table -AutoSize
    return $wmiFilters
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
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>Group Policy 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>Group Policy Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>All GPOs</h2>
    $($AllResults.AllGPOs | ConvertTo-Html -Fragment)

    <h2>Unlinked GPOs</h2>
    $($AllResults.UnlinkedGPOs | ConvertTo-Html -Fragment)

    <h2>Empty GPOs</h2>
    $($AllResults.EmptyGPOs | ConvertTo-Html -Fragment)

    <h2>Conflicting GPO Settings</h2>
    $($AllResults.ConflictingSettings | ConvertTo-Html -Fragment)

    <h2>GPO Links</h2>
    $($AllResults.GPOLinks | ConvertTo-Html -Fragment)

    <h2>GPO Permissions</h2>
    $($AllResults.GPOPermissions | ConvertTo-Html -Fragment)

    <h2>GPO Versions</h2>
    $($AllResults.GPOVersions | ConvertTo-Html -Fragment)

    <h2>GPO WMI Filters</h2>
    $($AllResults.WMIFilters | 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" { $allResults.AllGPOs = Analyze-AllGPOs }
        "2" { $allResults.UnlinkedGPOs = Find-UnlinkedGPOs }
        "3" { $allResults.EmptyGPOs = Identify-EmptyGPOs }
        "4" { $allResults.ConflictingSettings = Check-ConflictingGPOSettings }
        "5" { $allResults.GPOLinks = Analyze-GPOLinks }
        "6" { $allResults.GPOPermissions = Review-GPOPermissions }
        "7" { $allResults.GPOVersions = Check-GPOVersions }
        "8" { $allResults.WMIFilters = Analyze-GPOWMIFilters }
        "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 Group Policy Analyzer Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of Group Policy:
    • Analysis of all GPOs
    • Identification of unlinked GPOs
    • Detection of GPOs with no settings
    • Checking for conflicting GPO settings
    • Analysis of GPO links
    • Review of GPO permissions
    • Checking GPO version numbers
    • Analysis of GPO WMI filters
  3. Comprehensive error handling for each analysis function.
  4. A function to generate an HTML report of all collected data.

Key features:

  • Detailed analysis of all GPOs in the domain
  • Identification of potential issues like unlinked or empty GPOs
  • Detection of conflicting policy settings
  • Review of GPO links and their order
  • Analysis of GPO permissions for security auditing
  • Version number checks to identify potential replication issues
  • WMI filter analysis
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • Active Directory administrators managing complex GPO environments
  • IT auditors reviewing Group Policy configurations
  • System administrators troubleshooting Group Policy issues
  • Security professionals assessing GPO-based security settings

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to query GPOs in your domain
  3. Have the GroupPolicy and ActiveDirectory PowerShell modules installed

This script provides a comprehensive overview of Group Policy configurations in an Active Directory environment, making it easier to identify issues, inconsistencies, or security concerns related to GPOs. It can significantly streamline the process of auditing and maintaining Group Policies in large or complex AD environments.