Tag Archive for: Scripting

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.

PowerShell Tester Tool Template

<#
.SYNOPSIS
PowerShell Tester Tool Template

.DESCRIPTION
This script provides a template for a PowerShell-based tester tool that can be customized
for various testing scenarios. It includes functions for defining tests, running them,
and generating reports.

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

.EXAMPLE
.\TesterToolTemplate.ps1
#>

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

<#
.SYNOPSIS
Displays the main menu of the tester tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== PowerShell Tester Tool ===" -ForegroundColor Cyan
    Write-Host "1. Run All Tests"
    Write-Host "2. Run Specific Test"
    Write-Host "3. View Test Results"
    Write-Host "4. Generate HTML Report"
    Write-Host "5. Exit"
}

<#
.SYNOPSIS
Defines the test cases. Add your test functions here.
#>
function Define-Tests {
    $global:tests = @{
        "Test1" = { Test-Case1 }
        "Test2" = { Test-Case2 }
        "Test3" = { Test-Case3 }
        # Add more test cases as needed
    }
}

<#
.SYNOPSIS
Example test case 1. Replace with your actual test logic.
#>
function Test-Case1 {
    $testName = "Test Case 1"
    $description = "Description of Test Case 1"
    try {
        # Your test logic here
        $result = $true
        $message = "Test Case 1 passed successfully"
    }
    catch {
        $result = $false
        $message = "Test Case 1 failed: $_"
    }
    return [PSCustomObject]@{
        TestName = $testName
        Description = $description
        Result = $result
        Message = $message
    }
}

<#
.SYNOPSIS
Example test case 2. Replace with your actual test logic.
#>
function Test-Case2 {
    $testName = "Test Case 2"
    $description = "Description of Test Case 2"
    try {
        # Your test logic here
        $result = $true
        $message = "Test Case 2 passed successfully"
    }
    catch {
        $result = $false
        $message = "Test Case 2 failed: $_"
    }
    return [PSCustomObject]@{
        TestName = $testName
        Description = $description
        Result = $result
        Message = $message
    }
}

<#
.SYNOPSIS
Example test case 3. Replace with your actual test logic.
#>
function Test-Case3 {
    $testName = "Test Case 3"
    $description = "Description of Test Case 3"
    try {
        # Your test logic here
        $result = $true
        $message = "Test Case 3 passed successfully"
    }
    catch {
        $result = $false
        $message = "Test Case 3 failed: $_"
    }
    return [PSCustomObject]@{
        TestName = $testName
        Description = $description
        Result = $result
        Message = $message
    }
}

<#
.SYNOPSIS
Runs all defined tests.
#>
function Run-AllTests {
    Write-Host "`nRunning All Tests..." -ForegroundColor Yellow
    $global:testResults = @()
    foreach ($test in $global:tests.GetEnumerator()) {
        Write-Host "Running $($test.Key)..." -ForegroundColor Cyan
        $result = & $test.Value
        $global:testResults += $result
        if ($result.Result) {
            Write-Host "  Passed: $($result.Message)" -ForegroundColor Green
        } else {
            Write-Host "  Failed: $($result.Message)" -ForegroundColor Red
        }
    }
}

<#
.SYNOPSIS
Runs a specific test based on user input.
#>
function Run-SpecificTest {
    Write-Host "`nAvailable Tests:" -ForegroundColor Yellow
    $global:tests.Keys | ForEach-Object { Write-Host "  $_" }
    $testName = Read-Host "`nEnter the name of the test to run"
    if ($global:tests.ContainsKey($testName)) {
        Write-Host "Running $testName..." -ForegroundColor Cyan
        $result = & $global:tests[$testName]
        $global:testResults += $result
        if ($result.Result) {
            Write-Host "  Passed: $($result.Message)" -ForegroundColor Green
        } else {
            Write-Host "  Failed: $($result.Message)" -ForegroundColor Red
        }
    } else {
        Write-Host "Test not found." -ForegroundColor Red
    }
}

<#
.SYNOPSIS
Displays the results of all run tests.
#>
function View-TestResults {
    if ($global:testResults.Count -eq 0) {
        Write-Host "`nNo tests have been run yet." -ForegroundColor Yellow
    } else {
        Write-Host "`nTest Results:" -ForegroundColor Yellow
        $global:testResults | Format-Table -AutoSize
    }
}

<#
.SYNOPSIS
Generates an HTML report of the test results.
#>
function Generate-HTMLReport {
    Write-Host "`nGenerating HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Results Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px; }
        h1 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .pass { color: green; }
        .fail { color: red; }
    </style>
</head>
<body>
    <h1>Test Results Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <table>
        <tr>
            <th>Test Name</th>
            <th>Description</th>
            <th>Result</th>
            <th>Message</th>
        </tr>
        $(foreach ($result in $global:testResults) {
            $resultClass = if ($result.Result) { "pass" } else { "fail" }
            "<tr>
                <td>$($result.TestName)</td>
                <td>$($result.Description)</td>
                <td class='$resultClass'>$(if ($result.Result) { "Pass" } else { "Fail" })</td>
                <td>$($result.Message)</td>
            </tr>"
        })
    </table>
</body>
</html>
"@

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

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

    switch ($choice) {
        "1" { Run-AllTests }
        "2" { Run-SpecificTest }
        "3" { View-TestResults }
        "4" { Generate-HTMLReport }
        "5" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This PowerShell Tester Tool Template includes:

  1. A menu-driven interface for easy navigation.
  2. Functions for defining and running tests.
  3. Placeholder test case functions that you can replace with your actual test logic.
  4. Ability to run all tests or a specific test.
  5. Function to view test results.
  6. HTML report generation for test results.

Key features:

  • Flexible structure for defining multiple test cases
  • Easy-to-use menu for running tests and viewing results
  • Detailed test result tracking, including test name, description, result, and message
  • HTML report generation for easy sharing and documentation of test results
  • Modular design for easy expansion and modification

To use this template effectively:

  1. Replace the placeholder test case functions (Test-Case1, Test-Case2, Test-Case3) with your specific test logic.
  2. Add more test cases as needed in the Define-Tests function.
  3. Customize the test result object properties if you need to capture additional information.
  4. Modify the HTML report generation function if you want to change the report format or add more details.
  5. Add any necessary module imports or additional global variables at the beginning of the script.

This template provides a solid foundation for creating various types of testing tools in PowerShell, whether you’re testing system configurations, application functionality, or any other scenario that requires structured testing and reporting.

Template Menu-Driven PowerShell Tool

<#
.SYNOPSIS
Template Menu-Driven PowerShell Tool

.DESCRIPTION
This script provides a template for a menu-driven PowerShell tool that can be customized
for various administrative or analysis tasks.

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

.EXAMPLE
.\TemplateMenuTool.ps1
#>

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

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Template Menu-Driven Tool ===" -ForegroundColor Cyan
    Write-Host "1. Set Target (e.g., computer, path, etc.)"
    Write-Host "2. Perform Analysis Task 1"
    Write-Host "3. Perform Analysis Task 2"
    Write-Host "4. Perform Analysis Task 3"
    Write-Host "5. Perform Analysis Task 4"
    Write-Host "6. Perform Analysis Task 5"
    Write-Host "7. Generate Comprehensive HTML Report"
    Write-Host "8. Exit"
}

<#
.SYNOPSIS
Sets the target for analysis (e.g., computer name, file path, etc.).
#>
function Set-Target {
    $target = Read-Host "Enter the target for analysis (e.g., computer name, file path)"
    if (-not [string]::IsNullOrWhiteSpace($target)) {
        $global:target = $target
        Write-Host "Target set to: $global:target" -ForegroundColor Green
    } else {
        Write-Host "Invalid target. Please try again." -ForegroundColor Red
    }
}

<#
.SYNOPSIS
Performs Analysis Task 1.

.OUTPUTS
Array of PSObjects containing analysis results.
#>
function Perform-AnalysisTask1 {
    Write-Host "`nPerforming Analysis Task 1..." -ForegroundColor Yellow
    # Add your analysis logic here
    $results = @([PSCustomObject]@{
        Property1 = "Value1"
        Property2 = "Value2"
    })
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Performs Analysis Task 2.

.OUTPUTS
Array of PSObjects containing analysis results.
#>
function Perform-AnalysisTask2 {
    Write-Host "`nPerforming Analysis Task 2..." -ForegroundColor Yellow
    # Add your analysis logic here
    $results = @([PSCustomObject]@{
        Property1 = "Value1"
        Property2 = "Value2"
    })
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Performs Analysis Task 3.

.OUTPUTS
Array of PSObjects containing analysis results.
#>
function Perform-AnalysisTask3 {
    Write-Host "`nPerforming Analysis Task 3..." -ForegroundColor Yellow
    # Add your analysis logic here
    $results = @([PSCustomObject]@{
        Property1 = "Value1"
        Property2 = "Value2"
    })
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Performs Analysis Task 4.

.OUTPUTS
Array of PSObjects containing analysis results.
#>
function Perform-AnalysisTask4 {
    Write-Host "`nPerforming Analysis Task 4..." -ForegroundColor Yellow
    # Add your analysis logic here
    $results = @([PSCustomObject]@{
        Property1 = "Value1"
        Property2 = "Value2"
    })
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Performs Analysis Task 5.

.OUTPUTS
Array of PSObjects containing analysis results.
#>
function Perform-AnalysisTask5 {
    Write-Host "`nPerforming Analysis Task 5..." -ForegroundColor Yellow
    # Add your analysis logic here
    $results = @([PSCustomObject]@{
        Property1 = "Value1"
        Property2 = "Value2"
    })
    $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>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>Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>Target: $global:target</p>

    <h2>Analysis Task 1 Results</h2>
    $($AllResults.Task1Results | ConvertTo-Html -Fragment)

    <h2>Analysis Task 2 Results</h2>
    $($AllResults.Task2Results | ConvertTo-Html -Fragment)

    <h2>Analysis Task 3 Results</h2>
    $($AllResults.Task3Results | ConvertTo-Html -Fragment)

    <h2>Analysis Task 4 Results</h2>
    $($AllResults.Task4Results | ConvertTo-Html -Fragment)

    <h2>Analysis Task 5 Results</h2>
    $($AllResults.Task5Results | 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-8)"

    switch ($choice) {
        "1" { Set-Target }
        "2" { $allResults.Task1Results = Perform-AnalysisTask1 }
        "3" { $allResults.Task2Results = Perform-AnalysisTask2 }
        "4" { $allResults.Task3Results = Perform-AnalysisTask3 }
        "5" { $allResults.Task4Results = Perform-AnalysisTask4 }
        "6" { $allResults.Task5Results = Perform-AnalysisTask5 }
        "7" { Generate-HTMLReport -AllResults $allResults }
        "8" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

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

This Template Menu-Driven Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Placeholder functions for five different analysis tasks.
  3. A function to set a target for analysis (which can be customized based on your needs).
  4. A function to generate an HTML report of all collected data.
  5. Basic error handling and user input validation.

Key features:

  • Easy-to-customize menu structure
  • Placeholder functions for various analysis tasks
  • Ability to set and use a global target variable
  • HTML report generation capability
  • Modular design for easy expansion and modification

To use this template effectively:

  1. Replace the placeholder analysis functions (Perform-AnalysisTask1, Perform-AnalysisTask2, etc.) with your specific analysis logic.
  2. Customize the Set-Target function to handle the type of target you need (e.g., computer name, file path, etc.).
  3. Modify the menu options and corresponding switch statement in the main program loop to match your specific tasks.
  4. Adjust the HTML report generation function to include the specific results you want to display.
  5. Add any necessary module imports or additional global variables at the beginning of the script.

This template provides a solid foundation for creating various types of menu-driven PowerShell tools for system administration, security analysis, or any other task that requires user interaction and multiple analysis steps.

Dr. Scripto and the Great PowerShell Tournament

Once upon a time, in the magical IT kingdom, there was a renowned IT academy where the best and brightest system administrators and script masters were trained. This academy was known for its rigorous training and legendary professor, Dr. Scripto, famous for his quirky methods and challenging exams.

Every year, the academy held a special event: the Great PowerShell Tournament. This tournament was a highly anticipated event, attracting participants from far and wide. The tournament was not only a test of technical skills but also a showcase of creativity and humor. The prize was the coveted Golden PowerShell Wand, a symbol of ultimate mastery.

Among the participants this year was Tibor, the humorous and talented scriptmaster who had previously impressed Dr. Scripto with his witty exam scripts. Tibor was determined to win the Golden PowerShell Wand and cement his place in IT academy history.

The tournament began with a grand opening ceremony, where Dr. Scripto, dressed in his signature eccentric outfit, welcomed the participants. “Welcome, brave scriptmasters! Today, you will face challenges that will test your skills, creativity, and humor. Let the Great PowerShell Tournament begin!” he announced with a twinkle in his eye.

The first challenge was called “The Server Shuffle.” Participants had to write a script that would automatically reorganize files on a server based on their file type. Tibor, known for his humorous touch, added a bit of flair to his script:

# The Server Shuffle Script

Write-Host "Welcome to The Server Shuffle! Let's get those files dancing!"

# Reorganizing files by type
$files = Get-ChildItem -Path .\ -File
foreach ($file in $files) {
    $extension = $file.Extension.TrimStart('.')
    $destination = ".\$extension"
    if (-not (Test-Path -Path $destination)) {
        New-Item -ItemType Directory -Path $destination
        Write-Host "Created new folder: $destination"
    }
    Move-Item -Path $file.FullName -Destination $destination
    Write-Host "Moved $($file.Name) to $destination "
}

Write-Host "The Server Shuffle is complete! Enjoy your organized files! "

The audience burst into laughter as they saw the script in action, moving files around with a playful touch. Dr. Scripto was impressed by Tibor’s creativity and humor once again.

The second challenge was “The Backup Boogie.” Participants had to create a script that would back up files and notify the user with a funny message. Tibor embraced the challenge with enthusiasm:

# The Backup Boogie Script

Write-Host "Get ready for the Backup Boogie! Time to save those precious files!"

# Backing up files
$source = ".\ImportantFiles"
$backup = ".\Backup"
if (-not (Test-Path -Path $backup)) {
    New-Item -ItemType Directory -Path $backup
    Write-Host "Created backup folder: $backup"
}
Copy-Item -Path "$source\*" -Destination $backup -Recurse
Write-Host "Backup complete! Your files are safe and sound!"

# Funny notification
$messages = @(
    "Your files are backed up and ready to boogie!",
    "Backup complete! Now go take a break and dance!",
    "Backup successful! Time for a victory dance!"
)
$randomMessage = Get-Random -InputObject $messages
Write-Host "Notification: $randomMessage"

The script’s playful notifications brought smiles to everyone’s faces, and even Dr. Scripto couldn’t help but chuckle. Tibor’s ability to combine functionality with humor was truly exceptional.

The final challenge was the “Debug Dance-Off.” Participants had to debug a complicated script filled with errors while keeping the audience entertained. Tibor took a deep breath and dove into the task, fixing errors while adding his signature humorous commentary:

# Debug Dance-Off Script

Write-Host "Welcome to the Debug Dance-Off! Let's fix these errors and have some fun!"

# Debugging and fixing errors
try {
    # Intentional error for debugging practice
    $undefinedVariable | Out-Null
} catch {
    Write-Host "Oops! Found an error! Let's fix it!"
    $undefinedVariable = "Now it's defined!"
    Write-Host "Fixed: $undefinedVariable"
}

# More debugging fun
try {
    $number = 42
    $result = $number / 0
} catch {
    Write-Host "Yikes! Division by zero! Let's handle that!"
    $result = "Infinity (or maybe just an error)"
    Write-Host "Handled: $result"
}

Write-Host "Debugging complete! You danced through the errors like a pro!"

The audience was in stitches, and Dr. Scripto applauded Tibor’s performance. After all the challenges were completed, it was time to announce the winner.

Dr. Scripto took the stage and addressed the participants. “You all did a fantastic job, but one scriptmaster stood out with his creativity, technical skill, and humor. The winner of the Great PowerShell Tournament and the Golden PowerShell Wand is… Tibor!”

The crowd erupted in cheers as Tibor received the Golden PowerShell Wand from Dr. Scripto. Tibor had not only showcased his scripting prowess but also brought joy and laughter to everyone at the academy.

And so, Tibor’s name was etched into the IT academy’s hall of fame, and his stories of humorous scripting continued to inspire future generations of scriptmasters.

Streamlining User Management with PowerShell: Bulk User Creation Script

In today’s fast-paced IT environments, efficiently managing user accounts is crucial. Whether you’re setting up a new department or onboarding a group of employees, creating multiple user accounts can be time-consuming. This is where PowerShell comes to the rescue! In this post, we’ll explore a script that automates the process of creating multiple Active Directory users from a CSV file.

The Problem: You need to create numerous user accounts in Active Directory, each with specific attributes, and doing this manually is error-prone and time-consuming.

The Solution: A PowerShell script that reads user information from a CSV file and creates corresponding Active Directory accounts.

Here’s the script:

# Import the Active Directory module
Import-Module ActiveDirectory

# Specify the path to your CSV file
$csvPath = "C:\Scripts\NewUsers.csv"

# Import the CSV file
$users = Import-Csv -Path $csvPath

# Loop through each user in the CSV
foreach ($user in $users) {
    # Generate a username (first initial + last name)
    $username = ($user.FirstName.Substring(0,1) + $user.LastName).ToLower()
    
    # Generate an email address
    $email = "$username@yourdomain.com"
    
    # Create a secure password
    $securePassword = ConvertTo-SecureString $user.Password -AsPlainText -Force
    
    # Specify the OU where the user account will be created
    $ou = "OU=NewUsers,DC=yourdomain,DC=com"
    
    # Create the new user account
    New-ADUser -Name "$($user.FirstName) $($user.LastName)" `
               -GivenName $user.FirstName `
               -Surname $user.LastName `
               -SamAccountName $username `
               -UserPrincipalName $email `
               -Path $ou `
               -AccountPassword $securePassword `
               -ChangePasswordAtLogon $true `
               -Enabled $true `
               -EmailAddress $email `
               -Title $user.JobTitle `
               -Department $user.Department
    
    Write-Host "Created user account for $($user.FirstName) $($user.LastName)"
}

Write-Host "User creation process complete!"

How it works:

  1. The script imports the Active Directory module.
  2. It reads user information from a specified CSV file.
  3. For each user in the CSV, it:
    • Generates a username and email address.
    • Creates a secure password object.
    • Creates a new AD user with specified attributes.
  4. It provides feedback for each created user.

To use this script:

  1. Prepare a CSV file (NewUsers.csv) with columns: FirstName, LastName, Password, JobTitle, Department.
  2. Modify the $csvPath variable to point to your CSV file.
  3. Adjust the $ou variable to specify the correct Organizational Unit.
  4. Update the email domain in the $email variable.
  5. Run the script in PowerShell with appropriate permissions.

Example CSV content:

CopyFirstName,LastName,Password,JobTitle,Department
John,Doe,P@ssw0rd123!,Manager,Sales
Jane,Smith,Str0ngP@ss!,Developer,IT

Important considerations:

  • Ensure you have the necessary permissions to create AD users.
  • Be cautious with password handling; consider using a more secure method in production environments.
  • Always test scripts in a non-production environment first.
  • Comply with your organization’s security policies and password requirements.

This script can save hours of manual work when onboarding multiple users. You can easily extend it to include additional attributes or perform extra actions like adding users to specific groups.

PowerShell’s ability to interact with Active Directory makes it an invaluable tool for IT administrators. By automating repetitive tasks like user creation, you can focus on more strategic aspects of your role.

Remember, with great power comes great responsibility. Always double-check your CSV data and script logic before running bulk operations in your Active Directory environment.