Tag: #Automation

  • iTunes Top Songs & Albums Purchases Python Script

    This Python script fetches and displays the current top songs or albums based on purchases from the iTunes Store. Users can select a category and the number of entries to view, with rankings clearly labeled to reflect purchase trends as of the check date.

    Click to view script…
    #!/usr/bin/env python3
    # iTunes Top Purchases Scraper
    # Purpose: Fetches and displays the current top songs or albums based on purchases from the iTunes Store.
    # Note: This script shows purchase-based rankings, not streaming data.
    
    import requests
    from datetime import datetime
    
    # Define categories with their display names and RSS feed paths
    categories = {
        1: {'name': 'Top Songs (Purchases)', 'path': 'topsongs'},
        2: {'name': 'Top Albums (Purchases)', 'path': 'topalbums'}
    }
    
    def main():
        """Main function to run the iTunes Top Purchases Scraper."""
        # Inform the user that the data reflects purchases, not streaming
        print("Welcome! This script shows top songs or albums based on purchases from the iTunes Store (not streaming data).")
        
        # Display category options
        print("\nSelect a category:")
        for key, value in categories.items():
            print(f"{key}. {value['name']}")
        
        # Get and validate category choice
        choice_input = input("Enter the number of your choice: ")
        try:
            choice = int(choice_input)
            if choice not in categories:
                raise ValueError
        except ValueError:
            print("Invalid choice. Please run the script again and enter 1 or 2.")
            return
        
        category = categories[choice]
        category_name = category['name']
        
        # Get and validate number of entries
        limit_input = input("Enter the number of entries to display (1-100, default 10): ")
        if limit_input.strip() == "":
            limit = 10
        else:
            try:
                limit = int(limit_input)
                if limit < 1 or limit > 100:
                    print("Limit must be between 1 and 100. Using default of 10.")
                    limit = 10
            except ValueError:
                print("Invalid input. Using default of 10.")
                limit = 10
        
        # Construct the RSS feed URL
        url = f"https://itunes.apple.com/us/rss/{category['path']}/limit={limit}/json"
        
        # Record the current date and time
        check_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Fetch data from the iTunes RSS feed
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return
        
        # Extract entries from the JSON response
        feed = data.get('feed', {})
        entries = feed.get('entry', [])
        
        if not entries:
            print("No data available for this category.")
            return
        
        # Display the results
        print(f"\n{category_name} as of {check_date}")
        print(f"{'Rank':<5} {'Name':<50} {'Artist':<30}")
        print("-" * 85)
        
        for i, entry in enumerate(entries, start=1):
            name = entry.get('im:name', {}).get('label', 'N/A')
            artist = entry.get('im:artist', {}).get('label', 'N/A')
            print(f"{i:<5} {name:<50} {artist:<30}")
    
    if __name__ == '__main__':
        main()
  • iOS App Store Comparison Tool Python Script

    This Python script enables users to compare multiple iOS apps by inputting their names, retrieving details like ratings, versions, and descriptions from the iTunes Search API. It displays a side-by-side overview of each app’s name, short description, rating count, rating stars, current version, and the date the check was initiated.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Initialize a list to store app names
    app_names = []
    while True:
        app_name = input("Enter app name: ")
        app_names.append(app_name)
        another = input("Do you want to add another app? (y/n): ").lower()
        if another != 'y':
            break
    
    # Record the current date and time when the check is initiated
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Initialize a list to store app data
    apps_data = []
    
    # Query the iTunes Search API for each app
    for app_name in app_names:
        try:
            response = requests.get(
                "https://itunes.apple.com/search",
                params={"term": app_name, "country": "us", "media": "software"}
            )
            response.raise_for_status()  # Raise an exception for HTTP errors
            data = response.json()
    
            if data["resultCount"] > 0:
                # Take the first result as the most relevant app
                app = data["results"][0]
                
                # Create a short description from the first 20 words of the full description
                words = app["description"].split()
                short_description = " ".join(words[:20]) + "..." if len(words) > 20 else " ".join(words)
                
                # Get the rating stars, formatting to one decimal place if available
                rating_stars = app.get("averageUserRating", "N/A")
                if rating_stars != "N/A":
                    rating_stars = f"{rating_stars:.1f}"
                
                # Compile the app information
                app_info = {
                    "app_name": app["trackName"],
                    "short_description": short_description,
                    "rating_count": app.get("userRatingCount", 0),
                    "rating_stars": rating_stars,
                    "current_version": app.get("version", "N/A"),
                    "check_date": current_time
                }
            else:
                app_info = {
                    "app_name": app_name,
                    "error": "App not found"
                }
        except requests.exceptions.RequestException as e:
            app_info = {
                "app_name": app_name,
                "error": f"Error fetching data: {e}"
            }
        
        apps_data.append(app_info)
    
    # Display the information for all apps
    for app_info in apps_data:
        if "error" in app_info:
            print(f"App Name: {app_info['app_name']}")
            print(f"Error: {app_info['error']}")
        else:
            print(f"App Name: {app_info['app_name']}")
            print(f"Short Description: {app_info['short_description']}")
            print(f"Rating Count: {app_info['rating_count']}")
            print(f"Rating Stars: {app_info['rating_stars']}")
            print(f"Current Version: {app_info['current_version']}")
            print(f"Check Date: {app_info['check_date']}")
        print("-" * 40)
  • iOS App Store Rating Checker Python Script

    This Python script allows users to input an iOS app name and retrieves its overall rating and total number of ratings from the iTunes Search API. It also displays the current date and time when the data was checked, providing a simple way to monitor app performance on the App Store.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Get the app name from the user
    app_name = input("Enter the app name: ")
    
    # Base URL for the iTunes Search API
    base_url = "https://itunes.apple.com/search"
    
    # Parameters for the API request
    params = {
        "term": app_name,
        "country": "us",
        "media": "software"
    }
    
    try:
        # Send GET request to the API
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors
    
        # Parse the JSON response
        data = response.json()
    
        # Check if any apps were found
        if data["resultCount"] > 0:
            # Extract the first app's data
            app = data["results"][0]
            rating = app.get("averageUserRating", "N/A")
            if rating != "N/A":
                rating = f"{rating:.1f}"  # Format rating to one decimal place
            count = app.get("userRatingCount", "N/A")
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
            # Print the results
            print(f"App Name: {app['trackName']}")
            print(f"Overall Rating: {rating}")
            print(f"Total Ratings: {count}")
            print(f"Date Checked: {current_time}")
        else:
            print("No apps found with that name.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
  • Weight Tracking Python Script

    This Python script allows users to record their weight in pounds, automatically converting it to kilograms, and tracks entries over time with timestamps. It also enables users to look up past weights by date, showing changes from previous entries, and stores all data persistently in a JSON file for long-term tracking.

    Click to view script…
    import json
    import os
    from datetime import datetime
    
    def lbs_to_kg(lbs):
        """Convert weight from pounds to kilograms."""
        return lbs * 0.453592
    
    def validate_date(date_str):
        """Validate date input and return a date object if valid."""
        try:
            return datetime.strptime(date_str, "%Y-%m-%d").date()
        except ValueError:
            return None
    
    # Load existing entries from the JSON file
    if os.path.exists("weight_log.json"):
        with open("weight_log.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new weight or (2) look up a past weight? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new weight
        while True:
            try:
                weight = float(input("Enter your weight in pounds: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        if len(entries) > 0:
            previous_weight = entries[-1]["weight_lbs"]
            diff = weight - previous_weight
        else:
            diff = None
        
        new_entry = {"date": date_str, "time": time_str, "weight_lbs": weight}
        entries.append(new_entry)
        
        with open("weight_log.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Weight recorded: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
        
        if diff is not None:
            if diff > 0:
                print(f"You gained {diff:.2f} lbs ({lbs_to_kg(diff):.2f} kg) since the last entry.")
            elif diff < 0:
                print(f"You lost {-diff:.2f} lbs ({-lbs_to_kg(diff):.2f} kg) since the last entry.")
            else:
                print("No change in weight since the last entry.")
        else:
            print("This is your first entry. No previous data to compare.")
    
    elif action == "2":
        # Look up a past weight
        if not entries:
            print("No weight entries found. Please record a weight first.")
        else:
            while True:
                date_input = input("Enter the date to look up (YYYY-MM-DD): ")
                lookup_date = validate_date(date_input)
                if lookup_date:
                    break
                else:
                    print("Invalid date format. Please enter the date in YYYY-MM-DD format.")
            
            # Find entries for the specified date
            matching_entries = [entry for entry in entries if entry["date"] == date_input]
            
            if matching_entries:
                print(f"\nWeight entries for {date_input}:")
                for entry in matching_entries:
                    weight = entry["weight_lbs"]
                    time = entry["time"]
                    print(f"- {time}: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
            else:
                print(f"No weight entries found for {date_input}.")
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Apple Product Spec Scraper Python Script

    This Python script searches Wikipedia for an Apple product by name, extracts key specifications like dimensions, weight, and camera details from the infobox, and formats the data for easy reading, with special handling for model-specific variations like “Pro” and “Pro Max.”

    This script relies on four Python libraries: requests fetches data from Wikipedia’s API, BeautifulSoup (from bs4) parses the HTML content to extract infobox details, sys handles command-line arguments for the product name input, and re provides regular expression support to clean up text by removing citation markers and extra whitespace. To install the external libraries, use pip: run pip install requests beautifulsoup4 in your terminal or command prompt, while sys and re are part of Python’s standard library and require no additional installation.

    Click to view script…
    import requests
    from bs4 import BeautifulSoup
    import sys
    import re
    
    # Define the fields we want to show
    desired_fields = [
        "First released",
        "Dimensions",
        "Weight",
        "Operating system",
        "System-on-chip",
        "Memory",
        "Storage",
        "Battery",
        "Rear camera",
        "Front camera",
        "Display",
    ]
    
    # Define fields that have model-specific values (e.g., Pro vs. Pro Max)
    model_specific_fields = ["Dimensions", "Weight", "Battery", "Display"]
    
    def search_wikipedia(query):
        """Search Wikipedia for the given query and return the title of the first result."""
        search_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "query",
            "list": "search",
            "srsearch": query,
            "format": "json"
        }
        response = requests.get(search_url, params=params)
        data = response.json()
        if data['query']['search']:
            return data['query']['search'][0]['title']
        return None
    
    def get_page_html(title):
        """Retrieve the HTML content of the Wikipedia page with the given title."""
        parse_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "parse",
            "page": title,
            "format": "json"
        }
        response = requests.get(parse_url, params=params)
        data = response.json()
        return data['parse']['text']['*']
    
    def extract_infobox(html):
        """Extract key-value pairs from the infobox in the HTML content."""
        soup = BeautifulSoup(html, 'html.parser')
        infobox = soup.find('table', {'class': 'infobox'})
        if infobox:
            rows = infobox.find_all('tr')
            info = {}
            for row in rows:
                header = row.find('th')
                data = row.find('td')
                if header and data:
                    key = header.text.strip()
                    value = data.text.strip()
                    info[key] = value
            return info
        return None
    
    def clean_text(text):
        """Remove citation numbers and extra spaces from the text."""
        return re.sub(r'\[\d+\]', '', text).strip()
    
    def format_model_values(value):
        """Format model-specific values for fields like dimensions, weight, etc."""
        if "Pro Max:" in value:
            pro_part, pro_max_part = value.split("Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- Pro: {pro_value}\n- Pro Max: {pro_max_value}"
        elif "16 Pro Max:" in value:
            pro_part, pro_max_part = value.split("16 Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("16 Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- 16 Pro: {pro_value}\n- 16 Pro Max: {pro_max_value}"
        return clean_text(value)
    
    def main():
        if len(sys.argv) < 2:
            print("Usage: python3 apple_product_finder.py <product name>")
            sys.exit(1)
        product_name = " ".join(sys.argv[1:])
        title = search_wikipedia(product_name + " Apple")
        if not title:
            print("No product found.")
            return
        html = get_page_html(title)
        infobox = extract_infobox(html)
        if infobox:
            print(f"Key information for {title}:")
            for key in desired_fields:
                if key in infobox:
                    value = infobox[key]
                    if key in model_specific_fields:
                        formatted_value = format_model_values(value)
                        print(f"{key}:\n{formatted_value}")
                    else:
                        print(f"{key}: {clean_text(value)}")
        else:
            print("No infobox found for this product.")
    
    if __name__ == "__main__":
        main()
  • iTunes TV Show Seasons Release Finder Swift Script

    This Swift script lets you search for a TV show by title from the macOS Terminal, displaying its initial release date and a chronological list of seasons with their release dates, all pulled from the iTunes Store API. Perfect for TV enthusiasts wanting quick access to show timelines!

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response for TV seasons
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [TVSeason]
    }
    
    struct TVSeason: Codable {
        let artistName: String      // The TV show's name
        let collectionName: String  // The season's name
        let releaseDate: Date       // The season's release date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <tv show title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single TV show title
    let tvShowTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL for searching TV seasons
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: tvShowTitle),
        URLQueryItem(name: "media", value: "tvShow"),
        URLQueryItem(name: "entity", value: "tvSeason"),
        URLQueryItem(name: "country", value: "us")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Exit code for the script
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let seasons = searchResponse.results
                    let showName = seasons[0].artistName
                    // Sort seasons by release date
                    let sortedSeasons = seasons.sorted { $0.releaseDate < $1.releaseDate }
                    // Display show info and initial release date
                    if let firstReleaseDate = sortedSeasons.first?.releaseDate {
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateStyle = .long
                        let formattedDate = dateFormatter.string(from: firstReleaseDate)
                        print("TV Show: \(showName)")
                        print("Initial Release Date: \(formattedDate)")
                    } else {
                        print("TV Show: \(showName)")
                        print("Release date not available.")
                    }
                    // List all seasons
                    print("Seasons:")
                    for season in sortedSeasons {
                        let seasonDateFormatter = DateFormatter()
                        seasonDateFormatter.dateStyle = .long
                        let seasonFormattedDate = seasonDateFormatter.string(from: season.releaseDate)
                        print("- \(season.collectionName): \(seasonFormattedDate)")
                    }
                    exitCode = 0
                } else {
                    print("No TV show found for \"\(tvShowTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)

  • iTunes Movie Release Lookup Swift Script

    This Swift script searches the iTunes Store for a movie by title, provided as a command-line argument, and prints the release date of the first matching result. It uses the iTunes Search API and handles errors gracefully with appropriate exit codes

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [Movie]
    }
    
    struct Movie: Codable {
        let trackName: String
        let releaseDate: Date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <movie title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single movie title
    let movieTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: movieTitle),
        URLQueryItem(name: "media", value: "movie"),
        URLQueryItem(name: "entity", value: "movie")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Explicitly typed as Int32 to match exit() requirement
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format from API
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let movie = searchResponse.results[0] // Take the first result
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateStyle = .long
                    let formattedDate = dateFormatter.string(from: movie.releaseDate)
                    print("Release date of \(movie.trackName): \(formattedDate)")
                    exitCode = 0
                } else {
                    print("No results found for \"\(movieTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion of the network task
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)
  • Windows Security Features Check PowerShell Script

    This PowerShell script provides a quick and colorful overview of key Windows 11 security features, including Microsoft Defender, Firewall, Secure Boot, BitLocker, VBS, Credential Guard, and TPM status. It uses error handling to ensure reliability and presents results in an easy-to-read format, highlighting whether each feature is enabled or disabled.

    Click to view script…
    # Quick Windows 11 Security Features Check
    
    # Check if the script is running with administrator privileges
    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Write-Warning "This script should be run as Administrator for full functionality."
    }
    
    # Microsoft Defender Status
    Write-Host "`nMicrosoft Defender Status:" -ForegroundColor Cyan
    $defenderStatus = Get-MpComputerStatus
    Write-Host "Antivirus Enabled: " -NoNewline
    if ($defenderStatus.AntivirusEnabled) { Write-Host "Yes" -ForegroundColor Green } else { Write-Host "No" -ForegroundColor Red }
    Write-Host "Real-Time Protection: " -NoNewline
    if ($defenderStatus.RealTimeProtectionEnabled) { Write-Host "Yes" -ForegroundColor Green } else { Write-Host "No" -ForegroundColor Red }
    Write-Host "Tamper Protected: " -NoNewline
    if ($defenderStatus.IsTamperProtected) { Write-Host "Yes" -ForegroundColor Green } else { Write-Host "No" -ForegroundColor Red }
    
    # Firewall Status
    Write-Host "`nFirewall Status:" -ForegroundColor Cyan
    $firewallStatus = Get-NetFirewallProfile
    foreach ($profile in $firewallStatus) {
        Write-Host "$($profile.Name) Profile: " -NoNewline
        if ($profile.Enabled) { Write-Host "Enabled" -ForegroundColor Green } else { Write-Host "Disabled" -ForegroundColor Red }
    }
    
    # Secure Boot Status
    Write-Host "`nSecure Boot:" -ForegroundColor Cyan
    try {
        $secureBoot = Confirm-SecureBootUEFI
        Write-Host "Status: " -NoNewline
        if ($secureBoot) { Write-Host "Enabled" -ForegroundColor Green } else { Write-Host "Disabled" -ForegroundColor Red }
    } catch {
        Write-Host "Status: Not supported or error occurred" -ForegroundColor Yellow
    }
    
    # BitLocker Status
    Write-Host "`nBitLocker Status:" -ForegroundColor Cyan
    $bitLockerStatus = Get-BitLockerVolume
    foreach ($volume in $bitLockerStatus) {
        Write-Host "$($volume.MountPoint) Protection: " -NoNewline
        if ($volume.ProtectionStatus -eq "On") { Write-Host "On" -ForegroundColor Green } else { Write-Host "Off" -ForegroundColor Red }
    }
    
    # VBS and Credential Guard
    Write-Host "`nVBS and Credential Guard:" -ForegroundColor Cyan
    try {
        $deviceGuard = Get-CimInstance -ClassName Win32_DeviceGuard -ErrorAction Stop
        $vbsStatus = if ($deviceGuard.VirtualizationBasedSecurityStatus -eq 2) { "Enabled" } else { "Disabled" }
        $credGuard = if ($deviceGuard.SecurityServicesRunning -contains 1) { "Enabled" } else { "Disabled" }
        Write-Host "VBS: " -NoNewline
        if ($vbsStatus -eq "Enabled") { Write-Host "Enabled" -ForegroundColor Green } else { Write-Host "Disabled" -ForegroundColor Red }
        Write-Host "Credential Guard: " -NoNewline
        if ($credGuard -eq "Enabled") { Write-Host "Enabled" -ForegroundColor Green } else { Write-Host "Disabled" -ForegroundColor Red }
    } catch {
        Write-Host "VBS and Credential Guard status not available on this system." -ForegroundColor Yellow
    }
    
    # TPM Status
    Write-Host "`nTPM Status:" -ForegroundColor Cyan
    $tpmStatus = Get-Tpm
    Write-Host "TPM Present: " -NoNewline
    if ($tpmStatus.TpmPresent) { Write-Host "Yes" -ForegroundColor Green } else { Write-Host "No" -ForegroundColor Red }
    Write-Host "TPM Ready: " -NoNewline
    if ($tpmStatus.TpmReady) { Write-Host "Yes" -ForegroundColor Green } else { Write-Host "No" -ForegroundColor Red }
    
    Write-Host "`nSecurity Features Check Complete" -ForegroundColor Cyan
  • Identify Pending Windows Updates PowerShell Script

    This PowerShell script utilizes the Windows Update Agent API to scan for available updates that are not yet installed, displaying a detailed list of pending updates including their titles, KB numbers, download status, and descriptions. It provides a quick and reliable way to check the update status of a Windows system without requiring manual intervention through the Settings app.

    Click to view script…
    # PowerShell script to check for Windows updates and list pending updates
    
    try {
        Write-Output "Checking for updates..."
        
        # Create a new update session
        $session = New-Object -ComObject Microsoft.Update.Session
        
        # Create an update searcher
        $searcher = $session.CreateUpdateSearcher()
        
        # Set the search criteria to find updates that are not installed and not hidden
        $criteria = "IsInstalled=0 and IsHidden=0"
        
        # Perform the search
        $result = $searcher.Search($criteria)
        
        # Check if the search was successful (ResultCode 2 means Succeeded)
        if ($result.ResultCode -eq 2) {
            $updates = $result.Updates
            if ($updates.Count -gt 0) {
                Write-Output "Found $($updates.Count) pending updates:"
                $counter = 1
                foreach ($update in $updates) {
                    # Get the KB article ID if available
                    $kb = if ($update.KBArticleIDs.Count -gt 0) { $update.KBArticleIDs[0] } else { "N/A" }
                    # Check if the update is downloaded
                    $status = if ($update.IsDownloaded) { "Downloaded" } else { "Not Downloaded" }
                    Write-Output "$counter. Title: $($update.Title) (KB$kb) - $status"
                    Write-Output "   Description: $($update.Description)"
                    Write-Output ""
                    $counter++
                }
            } else {
                Write-Output "No pending updates found."
            }
        } else {
            Write-Output "Update search failed with result code $($result.ResultCode)"
        }
    } catch {
        Write-Output "An error occurred: $($_.Exception.Message)"
    }
  • Retrieve Detailed System Specifications PowerShell Script

    This PowerShell script collects and displays comprehensive system specifications for a Windows machine, including details about the operating system, processor, memory, disk drives, graphics, network adapters, and motherboard/BIOS. It organizes the information into a clear, readable format, making it ideal for system diagnostics, inventory tracking, or personal reference.

    Click to view script…
    # Get OS Information
    $os = Get-WmiObject -Class Win32_OperatingSystem
    $installDate = [System.Management.ManagementDateTimeConverter]::ToDateTime($os.InstallDate)
    Write-Output "Operating System Information:"
    Write-Output "OS Name: $($os.Caption)"
    Write-Output "Version: $($os.Version)"
    Write-Output "Build Number: $($os.BuildNumber)"
    Write-Output "Installation Date: $installDate"
    Write-Output ""
    
    # Get Processor Information
    $processors = Get-WmiObject -Class Win32_Processor
    $totalCores = ($processors | Measure-Object -Property NumberOfCores -Sum).Sum
    $totalThreads = ($processors | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum
    $processorName = $processors[0].Name
    $maxClockSpeed = $processors[0].MaxClockSpeed
    Write-Output "Processor Information:"
    Write-Output "Processor: $processorName"
    Write-Output "Total Cores: $totalCores"
    Write-Output "Total Threads: $totalThreads"
    Write-Output "Max Clock Speed: $maxClockSpeed MHz"
    Write-Output ""
    
    # Get Memory Information
    $memory = Get-WmiObject -Class Win32_PhysicalMemory
    $totalRAM = [math]::Round(($memory | Measure-Object -Property Capacity -Sum).Sum / 1GB, 2)
    Write-Output "Memory Information:"
    Write-Output "Total RAM: $totalRAM GB"
    Write-Output ""
    
    # Get Disk Information
    $disks = Get-WmiObject -Class Win32_DiskDrive
    Write-Output "Disk Information:"
    foreach ($disk in $disks) {
        $sizeGB = [math]::Round($disk.Size / 1GB, 2)
        Write-Output "Disk Model: $($disk.Model)"
        Write-Output "Size: $sizeGB GB"
        Write-Output ""
    }
    
    # Get Graphics Information
    $gpus = Get-WmiObject -Class Win32_VideoController
    Write-Output "Graphics Information:"
    foreach ($gpu in $gpus) {
        Write-Output "Graphics Card: $($gpu.Name)"
        Write-Output "Resolution: $($gpu.VideoModeDescription)"
        Write-Output ""
    }
    
    # Get Network Information
    $adapters = Get-NetAdapter | Where-Object {$_.Status -eq 'Up'}
    Write-Output "Network Information:"
    foreach ($adapter in $adapters) {
        Write-Output "Adapter Name: $($adapter.Name)"
        Write-Output "MAC Address: $($adapter.MacAddress)"
        $ipAddresses = Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex | Where-Object {$_.AddressFamily -eq 'IPv4'}
        Write-Output "IP Addresses:"
        foreach ($ip in $ipAddresses) {
            Write-Output "  $($ip.IPAddress)"
        }
        Write-Output ""
    }
    
    # Get Motherboard and BIOS Information
    $motherboard = Get-WmiObject -Class Win32_BaseBoard
    $bios = Get-WmiObject -Class Win32_BIOS
    $biosDate = [System.Management.ManagementDateTimeConverter]::ToDateTime($bios.ReleaseDate)
    Write-Output "Motherboard and BIOS Information:"
    Write-Output "Motherboard Manufacturer: $($motherboard.Manufacturer)"
    Write-Output "Motherboard Model: $($motherboard.Product)"
    Write-Output "BIOS Manufacturer: $($bios.Manufacturer)"
    Write-Output "BIOS Version: $($bios.Version)"
    Write-Output "BIOS Release Date: $biosDate"