Claude Code: Call Claude From Your Own GUI With claude -p (PowerShell)

Advertisement
Call Claude from your own GUI with claude -p Automation
Advertisement

My work PC can't run the Claude desktop app. So I tried to build my own desktop-style window on top of Claude Code, the command-line tool: one place to manage several projects at once. I shipped 29 versions in four days. Then I stopped partway through the last one, and I never went back.

One part never gave me trouble, though: the window called Claude through claude -p, and that worked from start to finish. So I pulled that part out into a small window you can open by pasting a script into PowerShell. Type a question, click Send, and Claude's reply appears below. It can continue the last conversation and read files in a folder you choose.

A small PowerShell window that calls claude -p
Each reply shows the session ID. The third question continues the second one.

What claude -p is

claude -p (short for --print) runs Claude Code in non-interactive mode. Plain claude opens a chat screen where you type. With -p, it takes one prompt, prints the answer, and exits. The official docs describe it as the way to run Claude Code programmatically.

Because a program can call it, you can use Claude from your own GUI, a batch file, Task Scheduler, or any other script. I use it every morning to have Claude read a Search Console summary.

There are other ways to call Claude from your own code. The main differences are which account they use and how much you have to build yourself.

Method Signs in with Best for
claude (interactive) Your Claude Code login Working in a terminal while you chat
claude -p (this post) Your Claude Code login One request at a time from your own window or script, using the Claude Code already on your PC
Agent SDK (Python, TypeScript) An API key, for example Building the same agent loop into your own app
Claude API An API key (pay per use) Web services or bulk jobs. You build chat history and file access yourself

If you already use Claude Code and want to call it from your own tools without setting up an API key, claude -p is the easiest option. I wrote about building a chat window with the Agent SDK in Using Max plan API credits with the Agent SDK.

Before you start

  • Install Claude Code, run claude once, and sign in. -p uses that login.
  • Every call counts toward the same usage limits as normal Claude Code. A loop that calls it hundreds of times will reach the limit fast.
  • Any file you let Claude read is sent to Claude. The window script below can only read files in its work folder. It can't edit files or run commands.

Try it in PowerShell first

The simplest form is a single line. The answer prints, and you're back at the prompt. If you changed the language setting in Claude Code, replies follow that setting, even for English prompts.

claude -p "Give me one PowerShell line that shows today's date."

For use from a program, add --output-format json. You get the reply text along with a session ID. Pass that ID to --resume, and the next prompt continues the same conversation.

$r = claude -p "Pick one color. Reply with only its name." --output-format json | ConvertFrom-Json
$r.result       # the reply text
$r.session_id   # session ID, used to continue
claude -p "What is the complementary color of the one you picked?" --resume $r.session_id

The first prompt returns a color name, then the session ID prints. The second answer names the complementary color of that same color, so it remembers the first answer.

These are the JSON fields I use:

Field What it holds
result The reply text
session_id The session ID. Pass it to --resume to continue
is_error true if the run failed partway
total_cost_usd An estimate in API prices. The docs say it can differ from your actual bill, and on a subscription login it isn't what you pay

Long text or file contents can go through a pipe instead of an argument.

Get-Content .\memo.txt -Raw | claude -p "Summarize this schedule, one line per day."

A small window that calls claude -p (PowerShell)

Open PowerShell (5.1 or 7), paste the whole script, and press Enter. If you save it as a .ps1 file, use UTF-8 with BOM. Nothing else needs to be installed besides Claude Code.

# claude-p-gui-en.ps1 : a small window that calls claude -p (Windows PowerShell 5.1 / PowerShell 7)
# Free to use. Sign in to Claude Code first (run claude once and log in).

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# ===== Settings to change =====
$WorkDir    = "$env:USERPROFILE\Documents"   # Folder Claude works in (where the files you want it to read are)
$Model      = "sonnet"                       # sonnet / opus / haiku, etc.
$AllowTools = "Read"                         # Tools Claude may use. "Read" = read files only, "" = answer questions only
# Added to every request (role, tone)
$SystemHint = 'Answer briefly in English. Use plain text with no headings or bold. Write commands on their own line without ``` code fences.'
$TimeLimit  = 180                            # Stop automatically after this many seconds
# ==========================

$script:SessionId = $null
$script:Proc = $null
$script:Started = $null

$form = New-Object Windows.Forms.Form
$form.Text = "Ask Claude (claude -p)"
$form.Size = New-Object Drawing.Size(640, 560)
$form.Font = New-Object Drawing.Font("Segoe UI", 10)
$form.StartPosition = "CenterScreen"

$inBox = New-Object Windows.Forms.TextBox
$inBox.Multiline = $true
$inBox.ScrollBars = "Vertical"
$inBox.SetBounds(12, 12, 600, 110)
$form.Controls.Add($inBox)

$sendBtn = New-Object Windows.Forms.Button
$sendBtn.Text = "Send"
$sendBtn.SetBounds(12, 130, 100, 32)
$form.Controls.Add($sendBtn)

$stopBtn = New-Object Windows.Forms.Button
$stopBtn.Text = "Stop"
$stopBtn.Enabled = $false
$stopBtn.SetBounds(120, 130, 100, 32)
$form.Controls.Add($stopBtn)

$cont = New-Object Windows.Forms.CheckBox
$cont.Text = "Continue the last conversation"
$cont.SetBounds(236, 134, 240, 26)
$form.Controls.Add($cont)

$newBtn = New-Object Windows.Forms.Button
$newBtn.Text = "New chat"
$newBtn.SetBounds(492, 130, 120, 32)
$form.Controls.Add($newBtn)

$outBox = New-Object Windows.Forms.TextBox
$outBox.Multiline = $true
$outBox.ReadOnly = $true
$outBox.ScrollBars = "Vertical"
$outBox.BackColor = [Drawing.Color]::White
$outBox.SetBounds(12, 172, 600, 300)
$form.Controls.Add($outBox)

$status = New-Object Windows.Forms.Label
$status.Text = "Ready"
$status.SetBounds(12, 482, 600, 24)
$form.Controls.Add($status)

$timer = New-Object Windows.Forms.Timer
$timer.Interval = 300

function Start-Claude([string]$prompt) {
    $hint = $SystemHint
    $opts = "-p --output-format json --model $Model"
    if ($AllowTools -eq "") {
        # With no tools, Claude may pretend it read a file. Tell it plainly that it cannot.
        $hint += " (Note: in this conversation you have no tool for opening files. If asked about a file, say in your own words that you cannot read it. Do not guess its contents.)"
        $opts += ' --tools ""'
    } else {
        $opts += " --tools $AllowTools --allowedTools $AllowTools"
    }
    # If Claude Code is set to another language (the "language" setting), that wins over the hint, so ask for English here too
    $opts += ' --settings "{\"language\":\"English\"}"'
    if ($cont.Checked -and $script:SessionId) { $opts += " --resume " + $script:SessionId }
    # The hint goes in double quotes (inner double quotes become \")
    $opts += ' --append-system-prompt "' + $hint.Replace('"', '\"') + '"'

    $psi = New-Object Diagnostics.ProcessStartInfo
    $psi.FileName = "claude"
    $psi.Arguments = $opts
    $psi.WorkingDirectory = $WorkDir
    $psi.UseShellExecute = $false
    $psi.CreateNoWindow = $true
    $psi.RedirectStandardInput = $true
    $psi.RedirectStandardOutput = $true
    $psi.RedirectStandardError = $true
    $psi.StandardOutputEncoding = [Text.Encoding]::UTF8
    $psi.StandardErrorEncoding = [Text.Encoding]::UTF8
    # Started from inside Claude Code, the child inherits the parent session variables and its chat is not saved. Remove them.
    foreach ($v in "CLAUDECODE", "CLAUDE_PID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_CODE_CHILD_SESSION", "CLAUDE_CODE_ENTRYPOINT") {
        $psi.EnvironmentVariables.Remove($v)
    }

    $script:Proc = [Diagnostics.Process]::Start($psi)
    $script:OutTask = $script:Proc.StandardOutput.ReadToEndAsync()
    $script:ErrTask = $script:Proc.StandardError.ReadToEndAsync()
    # Send the question through stdin as UTF-8 (line breaks and symbols arrive as typed)
    $bytes = (New-Object Text.UTF8Encoding($false)).GetBytes($prompt)
    $script:Proc.StandardInput.BaseStream.Write($bytes, 0, $bytes.Length)
    $script:Proc.StandardInput.Close()

    $script:Started = Get-Date
    $script:Stopped = $false
    $sendBtn.Enabled = $false
    $stopBtn.Enabled = $true
    $status.Text = "Thinking..."
    $timer.Start()
}

$timer.Add_Tick({
    $sec = [int]((Get-Date) - $script:Started).TotalSeconds
    if (-not $script:Proc.HasExited) {
        if ($sec -ge $TimeLimit) { $script:Stopped = $true; $script:Proc.Kill() }
        $status.Text = "Thinking... $sec s"; return
    }
    $timer.Stop()
    $sendBtn.Enabled = $true
    $stopBtn.Enabled = $false
    $text = $script:OutTask.Result
    # Stopped runs return nothing. Keep the session ID so you can still continue.
    if ($script:Stopped) {
        $outBox.AppendText("(Stopped)`r`n`r`n")
        $status.Text = "Stopped after $sec s"
        return
    }
    try {
        $j = $text | ConvertFrom-Json
        if (-not $j.session_id) { throw "Empty reply" }
        $script:SessionId = $j.session_id
        $reply = $j.result
        if (-not $reply) { $reply = "(Empty reply. Please send it again.)" }
        $outBox.AppendText("Claude: " + ($reply -replace "`r?`n", "`r`n") + "`r`n`r`n")
        $cost = "{0:N4}" -f [double]$j.total_cost_usd
        $status.Text = "Done in $sec s / session " + $script:SessionId.Remove(8) + "... / est. API cost $" + $cost
        if ($j.is_error) { $status.Text = "Ended with an error: " + $j.subtype }
    } catch {
        $err = $script:ErrTask.Result
        $outBox.AppendText("(Could not read the reply)`r`n" + $err + $text + "`r`n")
        $status.Text = "Failed, exit code " + $script:Proc.ExitCode
    }
})

$sendBtn.Add_Click({
    $q = $inBox.Text.Trim()
    if ($q -eq "") { return }
    $outBox.AppendText("You: " + $q + "`r`n")
    $inBox.Clear()
    Start-Claude $q
})

$stopBtn.Add_Click({
    if ($script:Proc -and -not $script:Proc.HasExited) { $script:Stopped = $true; $script:Proc.Kill() }
})

$newBtn.Add_Click({
    $script:SessionId = $null
    $cont.Checked = $false
    $outBox.Clear()
    $status.Text = "New chat"
})

$form.Add_FormClosing({
    if ($script:Proc -and -not $script:Proc.HasExited) { $script:Proc.Kill() }
})

[void]$form.ShowDialog()

Feel free to use and change the script.

What to change

Line What it does Example
8 $WorkDir The folder Claude works in. Point it at the files you want it to read "D:\Work\Minutes"
9 $Model The model "haiku" for speed, "opus" for harder questions
10 $AllowTools Tools Claude may use "Read" (read only) or "" (answer questions only)
12 $SystemHint Text added to every request. Sets the role and tone 'Answer as the PowerShell helper for our team.'
13 $TimeLimit Stops the run after this many seconds 300

How it works

  • Send starts claude -p --output-format json as a separate process and writes the question to stdin as UTF-8. Line breaks, quotes, and symbols such as the ampersand arrive as typed.
  • It reads the reply text and session ID from the JSON. With "Continue the last conversation" checked, it adds the ID with --resume.
  • While it waits, a timer only checks whether the process has finished, so the window never freezes. Stop and the time limit end the process but keep the session ID.
  • --tools limits which tools exist, and --allowedTools lets them run without asking. -p has no screen for "may I use this?", so anything not allowed is simply denied.
  • Started from inside Claude Code, the window would inherit the parent session's environment variables, such as CLAUDECODE. In the larger app, that sometimes kept a child session from saving its history. I didn't see it happen with -p, but the script removes them to be safe.

Where I got stuck

1. With no tools, Claude pretended to read the file

At first, the default was --tools "" (no tools). I asked it to read memo.txt and tell me only Wednesday's task. It got the answer right 0 times out of 4. The real entry was "renew the server certificate." One reply made up a dentist appointment at 3 PM instead.

I changed the default to "Read", which can only read files in the work folder. For the no-tools setting, the script now adds a note saying Claude has no tool for opening files, so it shouldn't guess. After that, it said it couldn't read the file in all 3 tries. My first note was phrased as an order ("reply that you can't read it"), and Claude repeated that sentence back as its answer. Describing its situation worked better.

2. Stop wiped the session ID

After I clicked Stop, the next "continue" question started a new conversation. A stopped run prints nothing. In Windows PowerShell 5.1, piping an empty string into ConvertFrom-Json returns nothing instead of an error, and that empty value overwrote the session ID. The script now skips reading the reply after a stop, so the ID stays.

3. Replies came back in Japanese

The English window worked, but every reply was in Japanese, even with an English prompt asking for English. My Claude Code settings file sets the language to Japanese, and that setting won over the prompt. The window now passes --settings with the language set to English on every call. If your Claude Code language is already English, it changes nothing.

Smaller things What I did
Replies were full of Markdown (headings, bold, code fences), which looks messy in a plain text box The default prompt asks for plain text, with commands on their own line
Once, a reply never came back (still waiting after 300 seconds) Added $TimeLimit, which stops the run after 180 seconds
Once, the reply text came back empty (the session ID was there) An empty reply now shows a "send it again" message
Character counts came back different every time Claude is bad at counting. Count in PowerShell if you need an exact number

What the bigger app taught me

The app I abandoned used a Node.js server with an Edge app window. It kept claude -p running with --input-format stream-json and --output-format stream-json. That setup can stream replies as they're written, and it can show "may I edit this file?" requests as buttons in the window. It's a lot more work than the one-call-per-question window in this post.

The biggest lesson: tests of the features you built can't find the features you forgot. The window kept running after I closed it, there was no way to quit, and there was no tray icon. I found each of those just by using it. Over 10 rounds of hands-on testing, the problem count started at 16 and never reached zero. Starting with a window this small and adding to it as you use it every day is more likely to last.

Also, automated tests burn through usage. Each round of test play pushed my weekly usage higher, from 86% to 92%. claude -p draws from the same limits as normal Claude Code, so put a cap on how many requests any automated loop can send.

Summary

claude -p lets your own window or script call the Claude Code on your PC, with no API key. Use --output-format json to get the reply and the session ID, then --resume to continue. To let it touch files, limit tools with --tools and --allowedTools. The window script works as pasted, so change the work folder and prompt to fit your job.

References

Comments

Copied title and URL