Tag: #Automation

  • Mac System Specs and Performance Dashboard Bash Script

    This script provides an organized summary of your Mac’s system information and performance metrics—including OS details, CPU specifications, memory size, disk usage, uptime, and battery status.

    Click to view script…
    #!/bin/bash
    # system_specs.sh - Display Mac system specs and performance info
    
    # Clear the terminal for a fresh display
    clear
    
    echo "======================================"
    echo "   Mac System Specs and Performance   "
    echo "======================================"
    
    # Operating System Information
    os_name=$(sw_vers -productName)
    os_version=$(sw_vers -productVersion)
    build_version=$(sw_vers -buildVersion)
    echo "Operating System: $os_name $os_version (Build $build_version)"
    
    # Computer Name (if set)
    computer_name=$(scutil --get ComputerName 2>/dev/null)
    if [ -n "$computer_name" ]; then
        echo "Computer Name: $computer_name"
    fi
    
    echo "--------------------------------------"
    
    # CPU Information
    cpu_brand=$(sysctl -n machdep.cpu.brand_string)
    physical_cpu=$(sysctl -n hw.physicalcpu)
    logical_cpu=$(sysctl -n hw.logicalcpu)
    echo "CPU: $cpu_brand"
    echo "Physical Cores: $physical_cpu"
    echo "Logical Cores: $logical_cpu"
    
    echo "--------------------------------------"
    
    # Memory (RAM) Information
    mem_bytes=$(sysctl -n hw.memsize)
    # Convert bytes to gigabytes (1GB = 1073741824 bytes)
    mem_gb=$(echo "scale=2; $mem_bytes/1073741824" | bc)
    echo "Memory (RAM): $mem_gb GB"
    
    echo "--------------------------------------"
    
    # Disk Usage for the Root Partition
    echo "Disk Usage (Root Partition):"
    # Display header and the line for '/' partition
    df -h / | awk 'NR==1 || $NF=="/"'
    echo "--------------------------------------"
    
    # Uptime and Load Average
    echo "Uptime and Load Average:"
    uptime
    echo "--------------------------------------"
    
    # Battery Information (if available)
    if command -v pmset &> /dev/null; then
        battery_info=$(pmset -g batt | head -1)
        echo "Battery Info: $battery_info"
    fi
    
    echo "======================================"
  • Dynamic Folder Generator on macOS with AppleScript

    This AppleScript streamlines folder creation by prompting users for the number of folders, a base name, and a destination location. It then automatically creates sequentially numbered folders in the chosen directory, simplifying organization and file management on macOS.

    Click to view script…
    -- Ask the user how many folders they want to create
    set folderCountString to text returned of (display dialog "How many folders do you want to create?" default answer "1")
    try
        set folderCount to folderCountString as integer
    on error
        display dialog "Please enter a valid number."
        return
    end try
    
    -- Ask for a base name for the folders
    set baseName to text returned of (display dialog "Enter a base name for your folders:" default answer "Folder")
    
    -- Let the user choose the target location (e.g., Desktop, Documents, Downloads, etc.)
    set targetFolder to choose folder with prompt "Choose the folder where the new folders will be created:"
    
    -- Create the folders
    tell application "Finder"
        repeat with i from 1 to folderCount
            set folderName to baseName & " " & i
            try
                make new folder at targetFolder with properties {name:folderName}
            on error errMsg number errNum
                display dialog "Error creating folder \"" & folderName & "\": " & errMsg
            end try
        end repeat
    end tell
    
    display dialog "Successfully created " & folderCount & " folder(s) in " & (targetFolder as text)
  • Google Apps Script Slide Creator

    This script logs a greeting, creates a new Google Slide with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestSlideScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Slides presentation with a unique name based on the current date and time
      var presentation = SlidesApp.create("Test Presentation " + new Date());
    
      // Get the first (default) slide of the presentation
      var slide = presentation.getSlides()[0];
    
      // Try to set the title and subtitle placeholders on the default title slide, if they exist
      var titlePlaceholder = slide.getPlaceholder(SlidesApp.PlaceholderType.CENTERED_TITLE);
      if (titlePlaceholder) {
        titlePlaceholder.asShape().getText().setText("Test Presentation");
      }
      
      var subtitlePlaceholder = slide.getPlaceholder(SlidesApp.PlaceholderType.SUBTITLE);
      if (subtitlePlaceholder) {
        subtitlePlaceholder.asShape().getText().setText("Created by: " + userEmail);
      }
    
      // Optionally, append another slide with additional details
      var additionalSlide = presentation.appendSlide(SlidesApp.PredefinedLayout.TITLE_AND_BODY);
      
      // Set the title of the additional slide
      var titleShape = additionalSlide.getShapes()[0];
      titleShape.getText().setText("Additional Slide");
    
      // Set the body text of the additional slide
      var bodyShape = additionalSlide.getShapes()[1];
      bodyShape.getText().setText("This slide was added by the script.\nActive user email: " + userEmail);
    
      // Log the URL of the created presentation so you can easily open it
      Logger.log("Presentation created: " + presentation.getUrl());
    }

  • Google Apps Script Sheet Creator

    This script logs a greeting, creates a new Google Sheet with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Sheet with a unique name based on the current date and time
      var spreadsheet = SpreadsheetApp.create("Test Spreadsheet " + new Date());
      var sheet = spreadsheet.getActiveSheet();
    
      // Append some rows to the sheet
      sheet.appendRow(["This spreadsheet was created by a test script in Google Apps Script."]);
      sheet.appendRow(["Active user email:", userEmail]);
    
      // Log the URL of the created spreadsheet so you can easily open it
      Logger.log("Spreadsheet created: " + spreadsheet.getUrl());
    }
  • Check Public IP with PowerShell Script

    A straightforward PowerShell script that lets you quickly determine your current public IP address in a simple and hassle-free way.

    Click to view script…
    # Get-PublicIP.ps1
    # This script retrieves and displays your public IP address
    
    # Query the API to get your public IP address in JSON format.
    $response = Invoke-RestMethod -Uri "https://api.ipify.org?format=json"
    
    # Display the IP address.
    Write-Host "Your public IP address is: $($response.ip)"

  • Retrieve Detailed Windows Network Information with PowerShell

    This PowerShell script gathers comprehensive network details from your Windows machine—including default route, local IP, subnet mask, broadcast address, MAC address, DNS servers, and public IP—while also performing a ping test to 8.8.8.8 for latency analysis. It’s a handy tool for troubleshooting and monitoring your network.

    Click to view script…
    # NetworkInfoDetailed.ps1 - Detailed network information for Windows
    
    # Helper function: Convert a CIDR prefix (e.g. 24) to a dotted-decimal subnet mask (e.g. 255.255.255.0)
    function Convert-PrefixToSubnetMask {
        param (
            [int]$PrefixLength
        )
        $max = [uint32]::MaxValue
        # For a given prefix, the netmask is: netmask = max - (2^(32 - prefix) - 1)
        $netmaskInt = $max - ([uint32]([math]::Pow(2, (32 - $PrefixLength)) - 1))
        $octet1 = ($netmaskInt -shr 24) -band 0xFF
        $octet2 = ($netmaskInt -shr 16) -band 0xFF
        $octet3 = ($netmaskInt -shr 8) -band 0xFF
        $octet4 = $netmaskInt -band 0xFF
        return "$octet1.$octet2.$octet3.$octet4"
    }
    
    # Helper function: Convert an IP string to a 32-bit unsigned integer.
    function Convert-IPStringToInt {
        param ([string]$ip)
        $bytes = $ip.Split('.') | ForEach-Object { [uint32]$_ }
        return ([uint32]($bytes[0] -shl 24)) -bor ([uint32]($bytes[1] -shl 16)) -bor ([uint32]($bytes[2] -shl 8)) -bor $bytes[3]
    }
    
    # Helper function: Convert a 32-bit unsigned integer to an IP string.
    function Convert-IntToIPAddress {
        param ([uint32]$ipInt)
        $a = ($ipInt -shr 24) -band 0xFF
        $b = ($ipInt -shr 16) -band 0xFF
        $c = ($ipInt -shr 8) -band 0xFF
        $d = $ipInt -band 0xFF
        return "$a.$b.$c.$d"
    }
    
    # Begin output with colored text using Write-Host.
    Write-Host "Gathering default route information..." -ForegroundColor Blue
    
    # Get the default route (DestinationPrefix "0.0.0.0/0") for IPv4.
    $defaultRoute = Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | 
        Where-Object { $_.NextHop -ne "0.0.0.0" } | 
        Sort-Object -Property RouteMetric | 
        Select-Object -First 1
    
    if (-not $defaultRoute) {
        Write-Host "Error: No active network interface found. Are you connected to a network?" -ForegroundColor Red
        exit 1
    }
    
    $gateway    = $defaultRoute.NextHop
    $ifaceIndex = $defaultRoute.InterfaceIndex
    
    # Retrieve the network adapter based on InterfaceIndex.
    $interface = Get-NetAdapter -InterfaceIndex $ifaceIndex -ErrorAction SilentlyContinue
    if (-not $interface) {
        Write-Host "Error: Could not retrieve network adapter information." -ForegroundColor Red
        exit 1
    }
    $ifaceName = $interface.Name
    
    Write-Host "Default Interface: $ifaceName" -ForegroundColor Green
    Write-Host "Gateway: $gateway" -ForegroundColor Green
    
    # Get the IPv4 address information.
    $ipInfo = Get-NetIPAddress -InterfaceIndex $ifaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Where-Object { $_.IPAddress } |
        Select-Object -First 1
    if (-not $ipInfo) {
        Write-Host "Error: Could not retrieve IP address information." -ForegroundColor Red
        exit 1
    }
    $ip           = $ipInfo.IPAddress
    $prefixLength = $ipInfo.PrefixLength
    
    Write-Host "IP Address: $ip" -ForegroundColor Green
    
    # Convert the prefix length to a subnet mask.
    $netmask = Convert-PrefixToSubnetMask -PrefixLength $prefixLength
    Write-Host "Subnet Mask: $netmask" -ForegroundColor Green
    
    # Calculate the broadcast address.
    $ipInt = Convert-IPStringToInt -ip $ip
    
    $max = [uint32]::MaxValue
    # Compute the netmask integer as: max - (2^(32 - prefix) - 1)
    $netmaskInt = $max - ([uint32]([math]::Pow(2, (32 - $prefixLength)) - 1))
    # The inverse mask (host portion) is:
    $inv = $max - $netmaskInt
    
    # Calculate the broadcast integer: (IP AND netmask) OR inverse mask.
    $broadcastInt = ([uint32]($ipInt -band $netmaskInt)) -bor $inv
    
    $broadcast = Convert-IntToIPAddress -ipInt $broadcastInt
    Write-Host "Broadcast Address: $broadcast" -ForegroundColor Green
    
    # Get the MAC (hardware) address.
    $mac = $interface.MacAddress
    Write-Host "MAC Address: $mac" -ForegroundColor Green
    
    # Retrieve DNS servers for the interface.
    $dnsInfo = Get-DnsClientServerAddress -InterfaceIndex $ifaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
    $dnsServers = $dnsInfo.ServerAddresses -join ' '
    Write-Host "DNS Servers: $dnsServers" -ForegroundColor Green
    
    # Get the public IP address using an external service (api.ipify.org).
    try {
        $public_ip = Invoke-RestMethod -Uri "https://api.ipify.org"
        Write-Host "Public IP Address: $public_ip" -ForegroundColor Green
    } catch {
        Write-Host "Error retrieving public IP address." -ForegroundColor Red
    }
    
    # Perform a ping test to 8.8.8.8 and calculate the average latency.
    Write-Host "Performing ping test to 8.8.8.8..." -ForegroundColor Blue
    try {
        $pingResults = Test-Connection -ComputerName 8.8.8.8 -Count 3 -ErrorAction Stop
        if ($pingResults) {
            $avgLatency = ($pingResults | Measure-Object -Property ResponseTime -Average).Average
            Write-Host ("Average Latency (ping): {0:N2} ms" -f $avgLatency) -ForegroundColor Green
        } else {
            Write-Host "Ping test failed." -ForegroundColor Red
        }
    } catch {
        Write-Host "Ping test failed." -ForegroundColor Red
    }
    
    Write-Host "Detailed network information gathered successfully." -ForegroundColor Blue
  • Simple Scheduled Website Opener AppleScript

    This AppleScript prompts you to enter a delay in seconds and a website URL, then opens the specified website in your default browser after the delay. A confirmation dialog informs you that the site will launch after you close it, making it a straightforward scheduling tool for web access.

    Click to view script…
    -- Simple Scheduled Website Opener
    -- Prompts the user for a delay (in seconds) and a website URL, then opens the URL after the delay.
    
    -- Ask the user for the delay in seconds
    set delayResponse to display dialog "Enter the number of seconds to wait before opening the website:" default answer "10"
    set delaySeconds to (text returned of delayResponse) as number
    
    -- Ask the user for the website URL
    set urlResponse to display dialog "Enter the website URL to open:" default answer "https://"
    set websiteURL to text returned of urlResponse
    
    -- Confirmation dialog informing the website will open after the dialog is closed
    display dialog "The website " & websiteURL & " will open in " & delaySeconds & " seconds after you close this dialog." buttons {"Cancel", "OK"} default button "OK"
    if button returned of result is "Cancel" then return
    
    -- Wait for the specified delay
    delay delaySeconds
    
    -- Open the website in the default browser
    do shell script "open " & quoted form of websiteURL

  • Rickroll Launcher AppleScript

    This AppleScript command uses a shell command to open a popular YouTube video in your default browser, effectively “Rickrolling” the user. It’s a playful example of how to execute shell scripts from within AppleScript.

    Click to view script…
    do shell script "open https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  • Simulating a macOS Crash Using AppleScript

    This AppleScript launches the macOS screensaver to create the appearance of an unresponsive system, then plays a voice message saying, “Uh oh. Something went wrong.” The combination can be used for testing reactions or demonstrating AppleScript’s ability to control system functions.

    Click to view script…
    do shell script "open /System/Library/CoreServices/ScreenSaverEngine.app"
    delay 2
    say "Uh oh. Something went wrong."

  • Gather Weather Bash Script

    This Bash script uses the wttr.in service to automatically fetch and display your current weather based on your IP geolocation, directly in your macOS terminal. It first checks for the curl utility and then outputs the ASCII weather forecast

    Click to view script…
    #!/bin/bash
    # current_weather.sh - Query current weather for your current location on macOS.
    # This script uses the wttr.in API to retrieve weather information based on your IP geolocation.
    # Usage: ./current_weather.sh
    
    # Define colors for output
    BLUE='\033[0;34m'
    NC='\033[0m'  # No Color
    
    # Ensure curl is installed
    if ! command -v curl &>/dev/null; then
      echo "Error: curl is not installed. Please install curl to use this script."
      exit 1
    fi
    
    echo -e "${BLUE}Fetching current weather for your location...${NC}"
    weather=$(curl -s wttr.in)
    
    if [ -z "$weather" ]; then
      echo "Error: Unable to retrieve weather information."
      exit 1
    fi
    
    echo "$weather"