Tag: #Informational

  • Hello Swift Script

    This simple Swift script prints a greeting message (“Hello, Swift scripting!”) to the console when executed.

    Click to view script…
    #!/usr/bin/env swift
    print("Hello, Swift scripting!")

  • True or False Trivia Challenge Python Script

    This interactive quiz game lets you explore fun categories by answering unique True/False questions. With each question, you’ll receive immediate feedback and an insightful explanation to expand your knowledge.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Animal Trivia",
                "questions": [
                    {
                        "question": "Elephants are the only animals that can't jump.",
                        "answer": True,
                        "description": "True! Due to their massive weight and unique limb structure, elephants are physically incapable of jumping."
                    },
                    {
                        "question": "Bats are blind.",
                        "answer": False,
                        "description": "False! While bats use echolocation, they also have functional eyes and can see."
                    },
                    {
                        "question": "A group of flamingos is called a 'flamboyance'.",
                        "answer": True,
                        "description": "True! The collective noun for flamingos is indeed 'flamboyance', which suits their vibrant appearance."
                    },
                    {
                        "question": "An octopus has three hearts.",
                        "answer": True,
                        "description": "True! Octopuses have two branchial hearts and one systemic heart."
                    },
                    {
                        "question": "Goldfish have a memory span of just three seconds.",
                        "answer": False,
                        "description": "False! Goldfish can actually remember things for months."
                    }
                ]
            },
            "2": {
                "name": "Space Facts",
                "questions": [
                    {
                        "question": "A day on Venus is longer than its year.",
                        "answer": True,
                        "description": "True! Venus rotates very slowly, making its day longer than the time it takes to orbit the Sun."
                    },
                    {
                        "question": "There is no sound in space.",
                        "answer": True,
                        "description": "True! Space is a vacuum, so sound cannot travel."
                    },
                    {
                        "question": "Mars has the tallest volcano in the solar system, Olympus Mons.",
                        "answer": True,
                        "description": "True! Olympus Mons on Mars stands about 22 kilometers high, making it the tallest volcano known."
                    },
                    {
                        "question": "Saturn is the only planet with rings.",
                        "answer": False,
                        "description": "False! While Saturn’s rings are the most prominent, Jupiter, Uranus, and Neptune also have ring systems."
                    },
                    {
                        "question": "The footprints on the Moon will disappear over time due to wind erosion.",
                        "answer": False,
                        "description": "False! The Moon has no atmosphere or wind, so the footprints will likely remain for millions of years."
                    }
                ]
            },
            "3": {
                "name": "History Myths",
                "questions": [
                    {
                        "question": "Napoleon Bonaparte was extremely short.",
                        "answer": False,
                        "description": "False! Napoleon was of average height for his era; the myth of his short stature comes from a misunderstanding of French measurements."
                    },
                    {
                        "question": "The Great Wall of China is visible from space.",
                        "answer": False,
                        "description": "False! The Great Wall is very narrow and follows the natural contours of the land, making it nearly impossible to see from space with the naked eye."
                    },
                    {
                        "question": "Vikings wore horned helmets.",
                        "answer": False,
                        "description": "False! There is no historical evidence that Vikings ever wore horned helmets; this image was popularized by 19th-century artists."
                    },
                    {
                        "question": "The French Revolution began in 1789.",
                        "answer": True,
                        "description": "True! The French Revolution, which reshaped France and influenced modern democracies, began in 1789."
                    },
                    {
                        "question": "Christopher Columbus made his first voyage to the Americas in 1492.",
                        "answer": True,
                        "description": "True! In 1492, Columbus set sail, marking the beginning of European exploration of the Americas."
                    }
                ]
            }
        }
    
        print("Welcome to the True/False Quiz Game!")
        
        while True:
            print("\nChoose a category for your quiz:")
            for key, cat in categories.items():
                print(f"{key}. {cat['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Thanks for playing! Goodbye!")
                break
            
            if choice not in categories:
                print("Invalid choice. Please try again.")
                continue
            
            selected_cat = categories[choice]
            print(f"\nYou selected: {selected_cat['name']}")
            # Create a local copy of the questions list so each question is shown only once.
            available_questions = selected_cat["questions"].copy()
            
            while available_questions:
                question = random.choice(available_questions)
                available_questions.remove(question)
                
                print("\n" + question["question"])
                user_answer = input("Type T for True or F for False: ").strip().lower()
                
                if user_answer not in ["t", "f"]:
                    print("Invalid input. Please type 'T' or 'F'.")
                    continue
                
                user_bool = True if user_answer == "t" else False
                
                if user_bool == question["answer"]:
                    print("Correct!")
                else:
                    print("Incorrect!")
                
                print("Explanation:", question["description"])
                
                # Check if there are more questions available.
                if available_questions:
                    another = input("\nWould you like another question from this category? (y/n): ").strip().lower()
                    if another != "y":
                        break
                else:
                    print("\nNo more questions left in this category.")
                    
    if __name__ == "__main__":
        main()
  • Historical News Fun Facts Python Script

    This Python script provides an interactive and engaging way to learn about major historical news events. Users can choose from a variety of categories and receive a random, interesting fact from each, making history both fun and informative.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Wars & Conflicts",
                "facts": [
                    "World War II (1939-1945) saw the largest mobilization of military forces in history.",
                    "The American Civil War (1861-1865) led to the abolition of slavery in the United States.",
                    "World War I (1914-1918) introduced modern warfare techniques like tanks and chemical warfare.",
                    "The Vietnam War sparked significant anti-war protests and shaped global politics for decades.",
                    "The Korean War (1950-1953) ended in an armistice, leaving the Korean Peninsula divided.",
                    "The Gulf War (1990-1991) was one of the first conflicts broadcast live on television.",
                    "The Napoleonic Wars reshaped Europe in the early 19th century.",
                    "The Crimean War (1853-1856) saw the first use of the telegraph for military communication.",
                    "The Thirty Years' War (1618-1648) was one of the longest and most destructive conflicts in Europe.",
                    "The Falklands War (1982) highlighted the lingering effects of colonial disputes."
                ]
            },
            "2": {
                "name": "Political Milestones",
                "facts": [
                    "The fall of the Berlin Wall in 1989 symbolized the end of the Cold War.",
                    "Nelson Mandela's release in 1990 marked a significant step toward ending apartheid in South Africa.",
                    "The Declaration of Independence in 1776 laid the foundation for the United States.",
                    "The French Revolution (1789-1799) radically transformed France’s political and social structure.",
                    "India gained independence from British colonial rule in 1947.",
                    "The establishment of the United Nations in 1945 aimed to promote peace and cooperation globally.",
                    "The suffragette movement secured voting rights for women in many countries during the early 20th century.",
                    "The end of the Cold War in 1991 reshaped global political alliances.",
                    "The formation of the European Union helped unify post-war Europe.",
                    "The Arab Spring in the early 2010s spurred political change across several Middle Eastern countries."
                ]
            },
            "3": {
                "name": "Tech & Science Breakthroughs",
                "facts": [
                    "The Apollo 11 moon landing in 1969 was watched live by millions around the globe.",
                    "The invention of the internet revolutionized communication and information sharing.",
                    "The Human Genome Project, completed in 2003, mapped the entire human genetic code.",
                    "The launch of the Hubble Space Telescope in 1990 expanded our view of the universe.",
                    "The discovery of penicillin in 1928 marked the beginning of modern antibiotics.",
                    "The advent of smartphones has transformed everyday communication and connectivity.",
                    "ENIAC, one of the first computers built in 1945, paved the way for the computer age.",
                    "Quantum computing promises to tackle problems beyond the capabilities of classical computers.",
                    "The discovery of the Higgs boson in 2012 confirmed the mechanism that gives particles mass.",
                    "CRISPR technology is revolutionizing genetics through precise gene editing."
                ]
            },
            "4": {
                "name": "Natural Disasters",
                "facts": [
                    "The 2004 Indian Ocean tsunami is one of the deadliest natural disasters in modern history.",
                    "The eruption of Mount Vesuvius in AD 79 famously buried the Roman cities of Pompeii and Herculaneum.",
                    "The 1906 San Francisco earthquake led to massive destruction and a major rebuild of the city.",
                    "Hurricane Katrina in 2005 devastated the Gulf Coast region of the United States.",
                    "The Great Galveston Hurricane of 1900 remains the deadliest natural disaster in U.S. history.",
                    "The 2011 Tōhoku earthquake and tsunami in Japan triggered a nuclear crisis at Fukushima.",
                    "The Dust Bowl of the 1930s severely impacted agriculture and displaced thousands in the American Midwest.",
                    "The 1980 eruption of Mount St. Helens was one of the most significant volcanic events in U.S. history.",
                    "The Lisbon earthquake of 1755 had far-reaching effects on European philosophy and society.",
                    "The Bhola cyclone of 1970 was one of the most catastrophic tropical cyclones ever recorded."
                ]
            },
            "5": {
                "name": "Cultural & Entertainment Events",
                "facts": [
                    "The Beatles’ appearance on The Ed Sullivan Show in 1964 kick-started Beatlemania in the U.S.",
                    "Woodstock in 1969 became an iconic symbol of the counterculture movement.",
                    "The launch of MTV in 1981 revolutionized the music industry and pop culture.",
                    "Blockbuster movies emerged in the 1970s, forever changing the film industry.",
                    "The first Academy Awards in 1929 established a global benchmark for cinematic achievement.",
                    "Reality TV's rise in the early 2000s reshaped modern television programming.",
                    "The global popularity of video games has transformed entertainment and technology industries.",
                    "Social media platforms in the 21st century have redefined celebrity culture and public interaction.",
                    "Streaming services have dramatically changed how audiences consume films and television shows.",
                    "Internet memes have become a defining aspect of digital culture in recent years."
                ]
            }
        }
        
        while True:
            print("\n=== Fun Fact Utility: Biggest News Events in History ===")
            print("Choose a category for a fun fact:")
            for key, value in categories.items():
                print(f"{key}. {value['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Goodbye!")
                break
            elif choice in categories:
                fact = random.choice(categories[choice]["facts"])
                print(f"\nFun Fact from {categories[choice]['name']}:")
                print(fact)
            else:
                print("Invalid choice. Please select a valid category.")
    
    if __name__ == "__main__":
        main()
  • USB Device Logger PowerShell Script

    A PowerShell script that logs detailed information about all connected USB devices, including their names, PNP device IDs, and descriptions, along with a timestamp. This tool is ideal for tracking USB connections over time for auditing or troubleshooting purposes.

    Click to view script…
    <#
    .SYNOPSIS
        Logs all USB devices connected to the system.
    
    .DESCRIPTION
        This script uses CIM/WMI to query for USB devices (by filtering for PNPDeviceIDs that start with "USB")
        and logs their details (Name, PNPDeviceID, Description) along with a timestamp. The log is appended to a file,
        which by default is stored in the same directory as the script (USBDeviceLog.txt).
    
    .NOTES
        Run this script with the necessary permissions. 
        Adjust the log file path if needed.
    #>
    
    # Define the log file location (you can change this to an absolute path if desired)
    $logFilePath = Join-Path -Path $PSScriptRoot -ChildPath "USBDeviceLog.txt"
    
    # Get the current timestamp
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    
    # Create the log entry header
    $logEntry = "USB Device Log - $timestamp`r`n" + ("=" * 50) + "`r`n"
    
    # Query for USB devices by filtering Win32_PnPEntity for entries with a PNPDeviceID starting with "USB"
    try {
        $usbDevices = Get-CimInstance -ClassName Win32_PnPEntity | Where-Object { $_.PNPDeviceID -like "USB*" }
    }
    catch {
        Write-Error "Error querying USB devices: $_"
        exit
    }
    
    if ($usbDevices) {
        foreach ($device in $usbDevices) {
            $logEntry += "Name         : " + $device.Name + "`r`n"
            $logEntry += "PNPDeviceID  : " + $device.PNPDeviceID + "`r`n"
            $logEntry += "Description  : " + $device.Description + "`r`n"
            $logEntry += ("-" * 40) + "`r`n"
        }
    }
    else {
        $logEntry += "No USB devices found." + "`r`n"
    }
    
    $logEntry += "`r`n"
    
    # Append the log entry to the log file
    try {
        Add-Content -Path $logFilePath -Value $logEntry
        Write-Host "USB devices logged successfully to $logFilePath" -ForegroundColor Green
    }
    catch {
        Write-Error "Failed to write to log file: $_"
    }
  • Drive Space Information PowerShell Script

    This PowerShell script retrieves and displays space information for all local fixed drives, including total size, free space, used space, and the percentage of free space.

    Click to view script…
    # Get-DriveSpaceInfo.ps1
    # This script retrieves space information for each local drive (DriveType=3) on the computer.
    # It displays the drive letter, total size, free space, used space, and percentage of free space.
    
    # Retrieve local disk drives (DriveType=3 indicates local fixed disks)
    $drives = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"
    
    if (!$drives) {
        Write-Host "No local drives found."
        exit
    }
    
    foreach ($drive in $drives) {
        $driveLetter = $drive.DeviceID
        $totalSize = $drive.Size
        $freeSpace = $drive.FreeSpace
    
        # Calculate used space and percentage of free space (if total size is not zero)
        if ($totalSize -gt 0) {
            $usedSpace = $totalSize - $freeSpace
            $percentFree = [Math]::Round(($freeSpace / $totalSize) * 100, 2)
            $totalSizeGB = [Math]::Round($totalSize / 1GB, 2)
            $freeSpaceGB = [Math]::Round($freeSpace / 1GB, 2)
            $usedSpaceGB = [Math]::Round($usedSpace / 1GB, 2)
        }
        else {
            $usedSpace = 0
            $percentFree = 0
            $totalSizeGB = 0
            $freeSpaceGB = 0
            $usedSpaceGB = 0
        }
    
        Write-Host "Drive: $driveLetter" -ForegroundColor Cyan
        Write-Host "  Total Size: $totalSizeGB GB"
        Write-Host "  Free Space: $freeSpaceGB GB ($percentFree`%)"
        Write-Host "  Used Space: $usedSpaceGB GB"
        Write-Host "-------------------------------------"
    }
  • Largest Files Explorer with Interactive Details PowerShell Script

    This PowerShell script scans a specified directory for files, lists the largest files in a neat, truncated table, and lets you view full details for any selected file or all files, providing a comprehensive yet user-friendly overview of disk usage.

    Click to view script…
    <#
    .SYNOPSIS
        Lists the largest files in a directory with a truncated display and full detail lookup.
    
    .DESCRIPTION
        This script recursively scans a specified directory (or the current directory by default),
        sorts all files by size in descending order, and displays the top N largest files as specified by the user.
        It shows a truncated file name and full path for a neat table view.
        After displaying the table, the user can choose an index (or "all") to view full details of the file(s).
    
    .NOTES
        Run as Administrator if scanning protected directories.
    #>
    
    # Function to convert bytes to a human-readable format.
    function Convert-BytesToHumanReadable {
        param ([long]$bytes)
        if ($bytes -ge 1PB) {
            return "{0:N2} PB" -f ($bytes / 1PB)
        }
        elseif ($bytes -ge 1TB) {
            return "{0:N2} TB" -f ($bytes / 1TB)
        }
        elseif ($bytes -ge 1GB) {
            return "{0:N2} GB" -f ($bytes / 1GB)
        }
        elseif ($bytes -ge 1MB) {
            return "{0:N2} MB" -f ($bytes / 1MB)
        }
        elseif ($bytes -ge 1KB) {
            return "{0:N2} KB" -f ($bytes / 1KB)
        }
        else {
            return "$bytes B"
        }
    }
    
    # Function to truncate long strings.
    function Truncate-String {
        param (
            [Parameter(Mandatory = $true)]
            [string]$str,
            [int]$maxLength = 50
        )
        if ($str.Length -gt $maxLength) {
            return $str.Substring(0, $maxLength - 3) + "..."
        }
        else {
            return $str
        }
    }
    
    # Prompt the user for the directory to scan (default is current directory).
    $directory = Read-Host "Enter the directory to scan (or press Enter for current directory)"
    if ([string]::IsNullOrWhiteSpace($directory)) {
        $directory = (Get-Location).Path
    }
    
    if (-not (Test-Path $directory)) {
        Write-Error "Directory '$directory' does not exist."
        exit
    }
    
    # Prompt the user for the number of items to list.
    $numberOfItems = Read-Host "Enter the number of largest files to list"
    if (-not [int]::TryParse($numberOfItems, [ref]$null)) {
        Write-Error "Invalid number entered. Please enter a valid integer."
        exit
    }
    $numberOfItems = [int]$numberOfItems
    
    Write-Host "Scanning directory '$directory' for files..." -ForegroundColor Cyan
    
    # Recursively retrieve all files within the specified directory.
    try {
        $files = Get-ChildItem -Path $directory -File -Recurse -ErrorAction SilentlyContinue
    } catch {
        Write-Error "Error retrieving files: $_"
        exit
    }
    
    if (!$files) {
        Write-Host "No files found in '$directory'."
        exit
    }
    
    # Sort the files by size (Length) descending and take the top N items.
    $largestFiles = $files | Sort-Object Length -Descending | Select-Object -First $numberOfItems
    
    # Build a table with an index and truncated file name and path.
    $i = 1
    $result = foreach ($file in $largestFiles) {
        [PSCustomObject]@{
            Index         = $i
            "File Name"   = Truncate-String -str $file.Name -maxLength 30
            "Full Path"   = Truncate-String -str $file.FullName -maxLength 60
            "Size (Bytes)"= $file.Length
            "Size (Human)"= Convert-BytesToHumanReadable -bytes $file.Length
        }
        $i++
    }
    
    # Display the results in a formatted table.
    Write-Host "`nTop $numberOfItems largest files in '$directory':" -ForegroundColor Green
    $result | Format-Table -AutoSize
    
    # Allow the user to view full details if needed.
    $choice = Read-Host "`nEnter a file index to view full details, type 'all' to view details for all files, or press Enter to exit"
    if (-not [string]::IsNullOrWhiteSpace($choice)) {
        if ($choice -match '^(all)$') {
            Write-Host "`nFull details for all files:" -ForegroundColor Cyan
            $largestFiles | Format-List *
        }
        elseif ([int]::TryParse($choice, [ref]$null)) {
            $index = [int]$choice
            if ($index -ge 1 -and $index -le $largestFiles.Count) {
                Write-Host "`nFull details for file at index $($index):" -ForegroundColor Cyan
                $largestFiles[$index - 1] | Format-List *
            }
            else {
                Write-Host "Invalid index entered." -ForegroundColor Yellow
            }
        }
    }
  • DNS Ping Test Utility PowerShell Script

    This PowerShell script allows users to select from a list of popular DNS servers and perform customizable ping tests to verify network connectivity. It supports both continuous and fixed-count pings, configurable intervals, optional logging, and displays summary statistics for comprehensive network diagnostics.

    Click to view script…
    <#
    .SYNOPSIS
        DNS Ping Test Utility
    
    .DESCRIPTION
        This script allows the user to choose from a list of popular DNS servers (e.g., Google, Cloudflare, OpenDNS, etc.)
        and then performs either continuous or fixed-count ping tests to verify network connectivity.
        Users can configure the interval between pings and optionally log the results to a file for further analysis.
        
    .NOTES
        Press Ctrl+C to exit continuous ping mode.
    #>
    
    # Define a list of DNS providers.
    $dnsProviders = @(
        [PSCustomObject]@{Name="Google DNS";       IP="8.8.8.8"},
        [PSCustomObject]@{Name="Cloudflare DNS";   IP="1.1.1.1"},
        [PSCustomObject]@{Name="OpenDNS";          IP="208.67.222.222"},
        [PSCustomObject]@{Name="Quad9 DNS";        IP="9.9.9.9"},
        [PSCustomObject]@{Name="Level3 DNS";       IP="4.2.2.2"}
    )
    
    # Display the DNS server options.
    Write-Host "Select a DNS server to ping:" -ForegroundColor Cyan
    for ($i = 0; $i -lt $dnsProviders.Count; $i++) {
        Write-Host ("{0}. {1} ({2})" -f ($i + 1), $dnsProviders[$i].Name, $dnsProviders[$i].IP)
    }
    
    # Prompt the user to choose a DNS server.
    [int]$choice = Read-Host "Enter the number corresponding to your choice"
    if ($choice -lt 1 -or $choice -gt $dnsProviders.Count) {
        Write-Error "Invalid selection. Exiting."
        exit
    }
    
    $selectedDNS = $dnsProviders[$choice - 1]
    Write-Host "You selected: $($selectedDNS.Name) ($($selectedDNS.IP))" -ForegroundColor Green
    
    # Ask if the user wants a fixed number of pings or continuous ping.
    $pingCountInput = Read-Host "Enter number of pings (or press Enter for continuous ping)"
    if ($pingCountInput -match '^\d+$') {
        $pingCount = [int]$pingCountInput
        $isContinuous = $false
    } else {
        $isContinuous = $true
    }
    
    # Ask for the interval between pings in seconds.
    $intervalInput = Read-Host "Enter interval in seconds between pings (default is 1 second)"
    if ([string]::IsNullOrWhiteSpace($intervalInput)) {
        $interval = 1
    } else {
        $interval = [double]$intervalInput
    }
    
    # Ask if the user wants to log the results to a file.
    $logChoice = Read-Host "Do you want to log results to a file? (Y/N)"
    $logEnabled = $false
    if ($logChoice -match '^[Yy]') {
        $logEnabled = $true
        $logFile = Read-Host "Enter log file path (or press Enter for default 'DNSPingLog.txt')"
        if ([string]::IsNullOrWhiteSpace($logFile)) {
            $logFile = "DNSPingLog.txt"
        }
        Write-Host "Logging enabled. Results will be saved to $logFile" -ForegroundColor Green
    }
    
    # Initialize an array to store successful ping response times if a fixed ping count is specified.
    if (-not $isContinuous) {
        $results = @()
    }
    
    Write-Host "Starting ping test to $($selectedDNS.IP)..." -ForegroundColor Cyan
    
    # Function to log output if logging is enabled.
    function Log-Output {
        param (
            [string]$message
        )
        if ($logEnabled) {
            $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            Add-Content -Path $logFile -Value "[$timestamp] $message"
        }
    }
    
    # Run the ping test.
    if ($isContinuous) {
        Write-Host "Press Ctrl+C to stop continuous ping."
        while ($true) {
            try {
                $pingResult = Test-Connection -ComputerName $selectedDNS.IP -Count 1 -ErrorAction SilentlyContinue
                $timestamp = Get-Date -Format "HH:mm:ss"
                if ($pingResult) {
                    $replyTime = $pingResult.ResponseTime
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Reply from $($selectedDNS.IP): time = $replyTime ms"
                } else {
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Request timed out for $($selectedDNS.IP)."
                }
                Write-Host $output
                Log-Output -message $output
            }
            catch {
                Write-Host "An error occurred: $_"
                Log-Output -message "Error: $_"
            }
            Start-Sleep -Seconds $interval
        }
    } else {
        for ($i = 1; $i -le $pingCount; $i++) {
            try {
                $pingResult = Test-Connection -ComputerName $selectedDNS.IP -Count 1 -ErrorAction SilentlyContinue
                $timestamp = Get-Date -Format "HH:mm:ss"
                if ($pingResult) {
                    $replyTime = $pingResult.ResponseTime
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Reply from $($selectedDNS.IP): time = $replyTime ms"
                    $results += $replyTime
                } else {
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Request timed out for $($selectedDNS.IP)."
                }
                Write-Host $output
                Log-Output -message $output
            }
            catch {
                Write-Host "An error occurred: $_"
                Log-Output -message "Error: $_"
            }
            Start-Sleep -Seconds $interval
        }
        
        # Provide summary statistics for the fixed-count ping test.
        if ($results.Count -gt 0) {
            $avgTime = [Math]::Round(($results | Measure-Object -Average).Average, 2)
            Write-Host "`nPing test completed. Average response time: $avgTime ms" -ForegroundColor Green
            Log-Output -message "Ping test completed. Average response time: $avgTime ms"
        } else {
            Write-Host "`nPing test completed. No successful pings." -ForegroundColor Yellow
            Log-Output -message "Ping test completed. No successful pings."
        }
    }
  • User Account Audit with Net User Parsing PowerShell Script

    This PowerShell script audits local user accounts by listing each account’s enabled/disabled status and extracting detailed last logon information using the net user command. It outputs a neatly formatted table, providing system administrators with a clear snapshot of user account activity for easier monitoring and troubleshooting.

    Click to view script…
    <#
    .SYNOPSIS
        Audits local user accounts by listing their enabled/disabled status and last logon time.
    
    .DESCRIPTION
        This script retrieves local user accounts using Get-LocalUser and then obtains last logon information
        for each account by parsing the output of the "net user" command. It outputs a table showing each account's name,
        whether it is enabled, and its last logon time (or "Never" if the account has not logged on).
    
    .NOTES
        Run as Administrator if necessary.
    #>
    
    function Get-LastLogonNetUser {
        param (
            [Parameter(Mandatory = $true)]
            [string]$UserName
        )
    
        # Execute the "net user" command for the given user
        $netUserOutput = net user $UserName 2>&1
    
        # Look for a line that contains "Last logon"
        $lastLogonLine = $netUserOutput | Where-Object { $_ -match "Last logon" }
        if ($lastLogonLine) {
            # The expected format is something like:
            #   Last logon                   2/12/2021 3:45:30 PM
            # Remove the label text and trim spaces to isolate the date/time string.
            $logonValue = ($lastLogonLine -replace ".*Last logon\s+", "").Trim()
            if ($logonValue -match "Never") {
                return "Never"
            }
            else {
                # Attempt to parse the logon value as a DateTime.
                try {
                    $dt = [DateTime]::Parse($logonValue)
                    return $dt
                }
                catch {
                    return $logonValue
                }
            }
        }
        else {
            return "Unknown"
        }
    }
    
    # Retrieve local user accounts.
    try {
        $localUsers = Get-LocalUser
    } catch {
        Write-Error "Failed to retrieve local users. Ensure this is run on a supported version of Windows with appropriate permissions."
        exit
    }
    
    # Prepare an array to store the audit results.
    $result = @()
    
    foreach ($user in $localUsers) {
        $userName = $user.Name
        $lastLogon = Get-LastLogonNetUser -UserName $userName
    
        $result += [PSCustomObject]@{
            Name      = $userName
            Enabled   = $user.Enabled
            LastLogon = $lastLogon
        }
    }
    
    # Output the results in a formatted table.
    $result | Format-Table -AutoSize
  • Typing Speed Test Python Script

    This Python script challenges your typing skills by randomly selecting one of ten unique sentences and measuring your typing speed in words per minute.

    Click to view script…
    #!/usr/bin/env python3
    import time
    import random
    
    def typing_speed_test():
        # List of 10 extremely unique sentences for the user to type
        sentences = [
            "The iridescent butterfly fluttered past the ancient clock tower as whispers of the past filled the air.",
            "Under a kaleidoscope sky, the lonely wanderer discovered a secret garden blooming with surreal neon flowers.",
            "Amidst the cosmic silence, a forgotten melody echoed through the labyrinth of interstellar dreams.",
            "In the midst of the bustling city, a solitary violinist played tunes that painted the sunrise in shades of hope.",
            "A cascade of luminous raindrops transformed the mundane street into a magical canvas of vibrant reflections.",
            "The mischievous fox leaped over a neon moon as the forest whispered untold legends in the darkness.",
            "Beneath the ancient cedar, time melted like caramel under the gentle touch of twilight.",
            "A carnival of shadows danced along the deserted boulevard, each step echoing forgotten tales.",
            "In a realm where gravity lost its grip, dreams soared like vivid kites against a starlit backdrop.",
            "The enigmatic street artist splashed abstract dreams onto concrete walls, creating a symphony of colors under midnight skies."
        ]
        
        # Randomly choose one sentence from the list
        sentence = random.choice(sentences)
        
        # Display instructions and the chosen sentence
        print("Typing Speed Tester")
        print("-------------------")
        print("Type the following sentence as quickly and accurately as you can:\n")
        print(sentence + "\n")
        input("Press Enter when you're ready to start...")
    
        print("\nStart typing below:\n")
        
        # Start the timer and capture the user's input
        start_time = time.time()
        typed_text = input()
        end_time = time.time()
        
        # Calculate elapsed time
        elapsed_time = end_time - start_time
    
        # Count the number of words in the sentence
        word_count = len(sentence.split())
        
        # Calculate words per minute (WPM)
        wpm = (word_count / elapsed_time) * 60
    
        print("\nResults:")
        print("Time taken: {:.2f} seconds".format(elapsed_time))
        print("Your typing speed is: {:.2f} words per minute (WPM)".format(wpm))
        
    if __name__ == "__main__":
        typing_speed_test()

  • Live Stock Price Tracker Python Script

    This Python script fetches live stock prices for a specified ticker using the yfinance library and logs the data with a timestamp into a CSV file for further analysis. It provides an easy way to monitor and record real-time market price movements.

    If you haven’t installed yfinance yet, you can easily add it by running the following command in your terminal:

    pip install yfinance
    Click to view script…
    #!/usr/bin/env python3
    import yfinance as yf
    import csv
    import os
    from datetime import datetime
    
    def fetch_stock_price(ticker_symbol):
        """
        Fetches the current stock price for the given ticker symbol using yfinance.
        It first tries to get the 'regularMarketPrice' from the ticker info.
        If that fails, it falls back to using the latest close price from recent historical data.
        """
        ticker = yf.Ticker(ticker_symbol)
        try:
            # Attempt to get the live price from the info dictionary
            info = ticker.info
            price = info.get("regularMarketPrice", None)
            if price is None:
                # Fallback: get the most recent closing price from historical data
                data = ticker.history(period="1d", interval="1m")
                price = data["Close"].iloc[-1]
        except Exception as e:
            print(f"Error fetching data for {ticker_symbol}: {e}")
            return None
        return price
    
    def store_stock_price(ticker_symbol, price, filename="stock_prices.csv"):
        """
        Stores the fetched stock price along with a timestamp and the ticker symbol into a CSV file.
        If the file does not exist, it creates one with appropriate headers.
        """
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        header = ["timestamp", "ticker", "price"]
        file_exists = os.path.isfile(filename)
        
        with open(filename, mode="a", newline="") as file:
            writer = csv.writer(file)
            if not file_exists:
                writer.writerow(header)
            writer.writerow([now, ticker_symbol, price])
        
        print(f"Stored price for {ticker_symbol} at {now} in {filename}.")
    
    def main():
        print("Stock Price Tracker")
        print("-------------------")
        print("Fetches live stock prices and stores them for analysis.\n")
        
        ticker_symbol = input("Enter the stock ticker (e.g., AAPL): ").strip().upper()
        if not ticker_symbol:
            print("No ticker entered. Exiting.")
            return
        
        price = fetch_stock_price(ticker_symbol)
        if price is not None:
            print(f"Current price of {ticker_symbol}: ${price:.2f}")
            store_stock_price(ticker_symbol, price)
        else:
            print("Failed to fetch stock price.")
    
    if __name__ == "__main__":
        main()