Skip to content

A PowerShell implementation of Claude Code: agent loop + tools + permissions.

License

Notifications You must be signed in to change notification settings

perezdap/PSClaudeCode

 
 

Repository files navigation

alt text



PSClaudeCode

Ever wondered how AI agents like Claude Code work their magic? Dive into this PowerShell implementation and build your own intelligent assistant from scratch!

Inspired by the original Claude Code article, this project demonstrates how to create a PowerShell AI agent using Anthropic's Claude API. Start with a simple command runner and evolve it into a sophisticated agent with function calling, file operations, and conversational capabilities.

In Action

Demo: the agent reads monthly CSV sales files and autonomously creates quarterly Excel workbooks using the ImportExcel module. The agent has no built-in logic for CSVs or Excel. It figures out what to do through iteration and tool use.

Working Examples

This shows PSClaudeCode in action, showcasing the AI agent's ability to autonomously analyze logs, extract insights, and generate structured reports through iterative tool use.

ipcc -dangerouslySkipPermissions "ck the system log. save analysis to a mardkown file in d:\temp\logAnalysis" &

Agent Creating Log Analysis Report

This screenshot shows the AI agent autonomously processing a log file, extracting key insights, and generating a structured analysis report. The agent uses iterative tool calls to read the file, analyze patterns, and create meaningful output without any hardcoded logic for log processing.

Note: The & symbol creating this as a background job. This demonstrates "parallel" agent execution.

Agent analyzing logs and creating a report

Sample Log Section

This image displays a sample section of the log file being analyzed, showing the raw data format that the agent works with. It demonstrates how the agent can handle various text-based inputs and adapt its analysis approach accordingly.

Sample section of log file being analyzed

The examples above highlight how the agent can handle complex, multi-step tasks without predefined logic, adapting to the specific requirements of log analysis and reporting.

Table of Contents

Features

  • PowerShell Module: Properly structured module with Invoke-PSClaudeCode cmdlet
  • Multi-Provider Support: Works with Anthropic Claude and any OpenAI-compatible endpoint
  • Flexible Endpoints: Use OpenAI, OpenRouter, Ollama, LM Studio, Azure OpenAI, and more
  • Agent Loop: Iterative task completion with AI-driven decision making
  • Structured Tools: Function calling for file operations (read/write) and command execution
  • Permission Checks: Safe operations with user confirmation for dangerous actions
  • Model Selection: Configurable model selection via parameters
  • Sub-agent Support: Delegates complex tasks to specialized sub-agents
  • PowerShell Native: Built entirely in PowerShell
  • Progressive Complexity: Three agent versions showing evolution from simple to advanced
  • Comment-Based Help: Full PowerShell help documentation with Get-Help Invoke-PSClaudeCode
  • Pipeline Input Support: Accept context via pipeline for enhanced task descriptions
  • Progress Indicators: Timestamped status messages showing agent processing stages

Prerequisites

  • PowerShell 5.1 or higher
  • API key for your chosen provider:
    • Anthropic: $env:ANTHROPIC_API_KEY
    • OpenAI/OpenRouter: $env:OPENAI_API_KEY
    • Ollama: No API key required (local)

Installation

  1. Clone the repository:

    git clone https://github.com/dfinke/PSClaudeCode.git
    cd PSClaudeCode
  2. Import the module:

    Import-Module .\PSClaudeCode.psd1

    Or install it permanently:

    # Copy to PowerShell modules directory
    $modulePath = "$env:USERPROFILE\Documents\PowerShell\Modules\PSClaudeCode"
    New-Item -ItemType Directory -Path $modulePath -Force
    Copy-Item -Path "PSClaudeCode.psd1" -Destination $modulePath
    Copy-Item -Path "PSClaudeCode.psm1" -Destination $modulePath
    Copy-Item -Path "Public\*" -Destination $modulePath -Recurse
    Copy-Item -Path "Private\*" -Destination $modulePath -Recurse
    Import-Module PSClaudeCode

Configuration

PSClaudeCode can be configured using environment variables. Set these once and use ipcc without specifying parameters every time.

Environment Variables

Variable Description Example
PSCLAUDECODE_PROVIDER Default provider (Anthropic or OpenAI) OpenAI
PSCLAUDECODE_BASEURL Default API endpoint URL http://localhost:11434/v1
PSCLAUDECODE_MODEL Default model name llama3
PSCLAUDECODE_APIKEY Default API key sk-...
ANTHROPIC_API_KEY Anthropic API key (fallback) sk-ant-...
OPENAI_API_KEY OpenAI API key (fallback) sk-...

Using a .env File

Create a .env file in your project directory or home folder to persist your configuration:

# .env file example for Ollama
PSCLAUDECODE_PROVIDER=OpenAI
PSCLAUDECODE_BASEURL=http://localhost:11434/v1
PSCLAUDECODE_MODEL=llama3
# .env file example for OpenRouter
PSCLAUDECODE_PROVIDER=OpenAI
PSCLAUDECODE_BASEURL=https://openrouter.ai/api/v1
PSCLAUDECODE_MODEL=anthropic/claude-3.5-sonnet
PSCLAUDECODE_APIKEY=sk-or-v1-your-key-here
# .env file example for Anthropic (default, minimal config)
ANTHROPIC_API_KEY=sk-ant-your-key-here

To load the .env file in PowerShell, add this to your session or $PROFILE:

# Load .env file into environment variables
if (Test-Path ".\.env") {
    Get-Content ".\.env" | ForEach-Object {
        if ($_ -match "^\s*([^#][^=]+)=(.*)$") {
            [Environment]::SetEnvironmentVariable($matches[1].Trim(), $matches[2].Trim(), "Process")
        }
    }
}

Or use a dedicated module like Set-PsEnv:

Install-Module Set-PsEnv -Scope CurrentUser
Set-PsEnv  # Loads .env from current directory

Quick Setup Examples

Ollama (local):

$env:PSCLAUDECODE_PROVIDER = "OpenAI"
$env:PSCLAUDECODE_BASEURL = "http://localhost:11434/v1"
$env:PSCLAUDECODE_MODEL = "llama3"

# Now just use:
ipcc -Task "List all files in this directory"

OpenRouter:

$env:PSCLAUDECODE_PROVIDER = "OpenAI"
$env:PSCLAUDECODE_BASEURL = "https://openrouter.ai/api/v1"
$env:PSCLAUDECODE_MODEL = "anthropic/claude-3.5-sonnet"
$env:PSCLAUDECODE_APIKEY = "sk-or-v1-your-key"

ipcc -Task "Analyze this code"

Anthropic (default):

$env:ANTHROPIC_API_KEY = "sk-ant-your-key"

ipcc -Task "Create a summary report"

Usage

After importing the module, use the Invoke-PSClaudeCode cmdlet or its alias ipcc:

Invoke-PSClaudeCode -Task "List all PowerShell files in this directory"
# or
ipcc -Task "List all PowerShell files in this directory"

Getting Help

The cmdlet includes comprehensive comment-based help:

Get-Help Invoke-PSClaudeCode
Get-Help Invoke-PSClaudeCode -Examples
Get-Help Invoke-PSClaudeCode -Parameter Task

Parameters

  • -Task: The task description for the AI agent to complete (required)
  • -Provider: LLM provider - Anthropic (default) or OpenAI (for any OpenAI-compatible endpoint)
  • -BaseUrl: Custom API endpoint URL (optional, defaults based on provider)
  • -ApiKey: API key (optional, falls back to environment variables)
  • -Model: Model to use (optional, defaults based on provider)
  • -dangerouslySkipPermissions: Switch to bypass user confirmation prompts for dangerous operations (use with caution)
  • Pipeline Input: Accepts pipeline input as additional context for the task

Provider Defaults

Provider Default BaseUrl Default Model API Key Env Var
Anthropic https://api.anthropic.com claude-sonnet-4-5-20250929 ANTHROPIC_API_KEY
OpenAI https://api.openai.com gpt-4o OPENAI_API_KEY

Examples

# Basic usage with Anthropic (default)
Invoke-PSClaudeCode -Task "Create a new file called 'test.txt' with 'Hello, World!'"

# Use OpenAI
Invoke-PSClaudeCode -Task "List all files in the current directory" -Provider OpenAI

# Use Ollama (local)
Invoke-PSClaudeCode -Task "Analyze this code" -Provider OpenAI -BaseUrl "http://localhost:11434/v1" -Model "llama3"

# Use OpenRouter
$env:OPENAI_API_KEY = "sk-or-v1-your-key"
Invoke-PSClaudeCode -Task "Summarize this" -Provider OpenAI -BaseUrl "https://openrouter.ai/api/v1" -Model "anthropic/claude-3.5-sonnet"

# Bypass permission checks (use with caution)
Invoke-PSClaudeCode -Task "Delete all .tmp files in the current directory" -dangerouslySkipPermissions

The repository also includes three standalone agent script implementations of increasing complexity (these use OpenAI API for reference):

  • agent-v0.ps1: Simple single-command agent (uses OpenAI)
  • agent-v1.ps1: Looping agent with JSON-based responses (uses OpenAI)
  • agent-v2.ps1: Advanced agent with structured tools and function calling (uses OpenAI)

Run any agent script directly:

.\agent-v0.ps1 "List all PowerShell files in this directory"

Examples

Basic File Operations

Invoke-PSClaudeCode -Task "Create a new file called 'test.txt' with the content 'Hello, World!', then read it back and display the contents."

Command Execution with Safety Checks

Invoke-PSClaudeCode -Task "List all files in the current directory and count how many there are"
# Agent will request permission for any potentially dangerous commands

Pipeline Input Examples

# Use file content directly as the task
Get-Content "data.txt" | Invoke-PSClaudeCode

# Provide context with a specific task
Get-Content "error.log" | Invoke-PSClaudeCode -Task "Analyze these error logs and identify the root cause"

# Process multiple files as context
Get-ChildItem "*.json" | Get-Content | Invoke-PSClaudeCode -Task "Compare these JSON configurations and highlight differences"

Using Different Providers and Models

# Use Anthropic Claude (default)
Invoke-PSClaudeCode -Task "Analyze the PowerShell scripts in this directory"

# Use OpenAI GPT-4o
Invoke-PSClaudeCode -Task "Analyze the PowerShell scripts in this directory" -Provider OpenAI -Model "gpt-4o"

# Use Ollama with Llama 3 (local, no API key needed)
Invoke-PSClaudeCode -Task "Create a summary of all .md files" -Provider OpenAI -BaseUrl "http://localhost:11434/v1" -Model "llama3"

# Use LM Studio (local)
Invoke-PSClaudeCode -Task "Summarize this code" -Provider OpenAI -BaseUrl "http://localhost:1234/v1" -Model "local-model"

# Use OpenRouter with explicit API key
Invoke-PSClaudeCode -Task "Analyze logs" -Provider OpenAI -BaseUrl "https://openrouter.ai/api/v1" -Model "anthropic/claude-3.5-sonnet" -ApiKey "sk-or-v1-xxx"

Pipeline Input for Context

The cmdlet now supports pipeline input to provide additional context:

# Use file content as the task
Get-Content "data.txt" | Invoke-PSClaudeCode

# Combine task with piped context
Get-Content "logfile.txt" | Invoke-PSClaudeCode -Task "Analyze this log file and create a summary report"

# Process multiple files
Get-ChildItem "*.csv" | Get-Content | Invoke-PSClaudeCode -Task "Analyze these CSV files and identify trends"

Legacy Script Examples

The standalone agent scripts are still available for reference:

Agent v0 - Simple Command Runner

.\agent-v0.ps1 "list all PowerShell files in this directory"
# AI suggests: Get-ChildItem *.ps1
# Run this command? (y/n)

Agent v1 - Looping Agent

.\agent-v1.ps1 "List all files in the current directory and count how many there are"
# Agent will run commands iteratively until task is complete

Agent v2 - Function Calling Agent

.\agent-v2.ps1 "Create a new file called 'test.txt' with the content 'Hello, World!', then read it back and display the contents."
# Agent uses structured tools for file operations and command execution

Agent Evolution

Check out the step-by-step guide to understand the evolution from basic to advanced agent implementations.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Be Sure to Check out

  • dfinke/psai: PSAI brings the power of autonomous agents to PowerShell, allowing you to seamlessly integrate AI capabilities into your scripts and terminal workflows.
  • dfinke/psaisuite: Simple, unified interface to multiple Generative AI providers including OpenAI, Anthropic, and others. PSAISuite makes it easy for developers to use multiple LLMs through a standardized interface.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A PowerShell implementation of Claude Code: agent loop + tools + permissions.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PowerShell 100.0%