Skip to content

Instantly share code, notes, and snippets.

@dfinke
Created June 29, 2025 19:02
Show Gist options
  • Save dfinke/c872806290a1f14f51d9c85d24979c78 to your computer and use it in GitHub Desktop.
Save dfinke/c872806290a1f14f51d9c85d24979c78 to your computer and use it in GitHub Desktop.
# 📦 Install-Module: PSAISuite
# 🔗https://github.com/dfinke/psaisuite
# Get-ChatProviders
# PSAISuite supports 13 providers, and their models.
# $model = "github:openai/gpt-4.1"
$model = "anthropic:claude-opus-4-20250514"
$scriptContent = Get-Content .\AnalyzeSampleScript.ps1
$prompt = Get-Content .\PowerShellScriptAnalyzerPrompt.md -Raw
$response = $scriptContent | Invoke-ChatCompletion -TextOnly $prompt $model
$response | Set-Content .\AnalysisResult.md
@dfinke
Copy link
Author

dfinke commented Jun 29, 2025

Code Analysis and Educational Enhancement Guide

Initial Documentation

Script Purpose and Requirements

Purpose: This PowerShell script identifies resource-intensive processes on your computer and saves the information to a CSV file.

Real-World Analogy: Think of this script as a "resource detective" - like a building inspector who walks through a facility identifying which rooms are using the most electricity and water, then creates a report of the biggest resource consumers.

Requirements:

  • PowerShell 5.0 or higher
  • Write permissions to the current directory (for creating H.csv)
  • Administrator privileges recommended for complete process visibility

Input: None required - the script automatically examines all running processes
Output: A CSV file named "H.csv" containing process names, CPU usage, and memory consumption

Educational Comments and Explanations

Enhanced Code with Educational Comments

# ===== RESOURCE-INTENSIVE PROCESS ANALYZER =====
# This script finds processes using significant CPU resources and creates a report
# Think of it as a "performance bottleneck finder" for your computer

# WHY: We need a container to store our findings, like a detective's notepad
# Initialize an empty array to collect process information
$resultsArray = @()  # The @() creates an empty array - like an empty filing cabinet

# HOW: Get all processes and examine each one
# Get-Process retrieves all running processes (like getting a list of all employees in a building)
Get-Process | ForEach-Object {
    # LEARNING OPPORTUNITY: The pipeline (|) passes each process to the next command
    # Like items on a conveyor belt moving to the next station
    
    # WHY: We only want processes using significant CPU time
    # Check if this process has used more than 100 seconds of CPU time
    if ($_.CPU -gt 100) {
        # REMEMBER! $_ represents "the current item" in the pipeline
        # Like saying "this particular item I'm looking at right now"
        
        # HOW: Create a custom object with the information we want to track
        # PSCustomObject is like filling out a form with specific fields
        $processInfo = [PSCustomObject]@{
            Name = $_.Name                                    # The process name (like employee name)
            CPU = $_.CPU                                      # Total CPU seconds used
            Memory = ($_.WorkingSet/1MB).ToString("N2") + " MB"  # Memory in megabytes
            # WorkingSet is memory in bytes, so we divide by 1MB to get megabytes
            # ToString("N2") formats the number with 2 decimal places
        }
        
        # Add this process information to our results collection
        $resultsArray += $processInfo
        # COMMON MISTAKE ALERT: Using += with arrays creates a new array each time
        # For better performance with large datasets, consider using ArrayList
    }
}

# WHY: Sort the results to show the biggest CPU users first
# Like organizing a report with the most important items at the top
$resultsArray | 
    Sort-Object CPU -Descending |  # Sort by CPU usage, highest first
    Export-Csv -Path "H.csv" -NoTypeInformation
    # Export-Csv creates a spreadsheet-like file
    # -NoTypeInformation prevents PowerShell type info from being added to the file

PowerShell-Specific Concepts Explained

The Pipeline Magic

The pipeline (|) in PowerShell is like an assembly line in a factory. Each station (command) does one specific job and passes the result to the next station. In our script:

  1. Get-Process puts all processes on the conveyor belt
  2. ForEach-Object examines each one
  3. Sort-Object reorganizes them
  4. Export-Csv packages them into a file

The Mysterious $_

Think of $_ as "the thing I'm currently looking at." When you're sorting through a box of toys, $_ would be whichever toy is in your hand at that moment.

Object Properties

PowerShell treats everything as objects with properties. A process object is like a person's ID card with different fields:

  • Name (like the person's name)
  • CPU (like hours worked)
  • WorkingSet (like office space occupied)

Process Breakdown

Step-by-Step Data Flow

  1. Collection Phase: Script gathers all running processes (

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment