# How to Use OfficeCLI Batch Mode for Multiple Operations and Error Handling

> Master OfficeCLI batch mode to perform multiple operations atomically. Learn about error handling, exit codes, and stop on error for efficient document processing with iOfficeAI OfficeCLI.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-07-11

---

**OfficeCLI batch mode executes multiple document operations atomically via a JSON array, supports both resident and non-resident execution paths, and returns structured exit codes (0, 1, or 2) with optional `--stop-on-error` halting on the first failure.**

OfficeCLI, the open-source command-line interface from the iOfficeAI/OfficeCLI repository, provides a robust `batch` command designed for high-throughput document automation. This command processes a JSON array of operations—such as `add`, `set`, `remove`, and `move`—while optimizing performance through deferred saves and comprehensive error handling.

## How OfficeCLI Batch Mode Processes Commands

The batch command in [`src/officecli/CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Batch.cs) accepts a JSON array where each element represents a single operation. The implementation distinguishes between three input sources and two execution paths (resident vs. non-resident) to maximize efficiency.

### Input Sources and Validation

You can supply the batch JSON through three mutually exclusive methods:

- **`--commands`**: Pass a JSON string directly as a command-line argument
- **`--input <file>`**: Read from a file path
- **`--input -`**: Read from standard input (stdin)

The source code enforces mutual exclusivity between these options and warns if stdin is redirected while another source is specified (lines 89-100). For example, piping from another command requires the stdin notation:

```bash
officecli dump source.docx --json | officecli batch target.docx --input -

```

### Resident vs. Non-Resident Execution Paths

The batch processor checks for a resident OfficeCLI server before execution:

**Resident Path** (lines 66-79): When a resident server manages the target file, the entire batch is sent as a single `"batch"` request to that process. The resident applies items in-memory and defers the actual disk write until the next save, close, or idle-autosave event.

**Non-Resident Path** (lines 101-112): If no resident exists, the CLI opens the document once, sets `DeferSave = true` (ensuring the document serializes only once upon disposal), and replays each batch item sequentially. For `.docx` files, the processor checks document-level protection once before any mutation (lines 104-110). Use the `--force` flag to bypass this protection, mirroring the behavior of `set --force`.

## Error Handling and Exit Codes in Batch Mode

OfficeCLI implements granular error tracking through the `ApplyBatchItems` method, capturing per-item failures while allowing configurable continuation behavior.

### Per-Item Error Handling

When an individual batch item throws an exception, the processor catches the error and records a `BatchResult` with `Success = false` and the exception message (lines 73-77). By default, the batch uses **continue-on-error** logic, processing remaining items even after failures. Set `--stop-on-error` to abort immediately on the first failure (lines 30-33).

After processing completes, the system computes an overall `batchSuccess` flag—true only if all items succeeded (lines 38-40).

### Exit Codes and Warnings

OfficeCLI returns three distinct exit codes:

- **`0`**: All items succeeded with no warnings
- **`1`**: At least one item failed or a protection error occurred
- **`2`**: No failures, but batch-level warnings were emitted (e.g., unrecognized LaTeX tokens)

Warnings—such as unrecognized LaTeX tokens collected during replay—are emitted as `CliWarning` messages on stderr and included in the JSON envelope when using `--json` (lines 43-52).

### JSON Output Envelope

When the `--json` flag is specified, results wrap in a standardized envelope (`{ "success": ..., "data": ... }`) applied consistently for both resident and non-resident runs (lines 28-34, 54-58).

## Practical OfficeCLI Batch Mode Examples

Create a batch file describing multiple operations:

```json
[
  {
    "command": "add",
    "parent": "/slide[1]",
    "type": "shape",
    "props": { "text": "Hello", "x": "1cm", "y": "2cm" }
  },
  { 
    "command": "set", 
    "path": "/slide[1]/shape[1]", 
    "props": { "bold": "true" } 
  },
  { 
    "command": "remove", 
    "path": "/slide[2]/shape[3]" 
  }
]

```

Execute batches using different input methods:

```bash

# 1. Pass a file

officecli batch presentation.pptx --input batch.json

# 2. Inline JSON

officecli batch document.docx --commands '[
  {"command":"set","path":"/body/p[1]","props":{"italic":"true"}},
  {"command":"add","parent":"/body","type":"paragraph","props":{"text":"Added"}}
]'

# 3. Stop on first error

officecli batch report.docx --input batch.json --stop-on-error

# 4. Force through protection

officecli batch protected.docx --input batch.json --force

```

## Summary

- OfficeCLI batch mode processes JSON arrays of operations via [`src/officecli/CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Batch.cs), supporting resident (in-memory) and non-resident (file-based) execution paths.
- Input can be provided via `--commands`, `--input <file>`, or `--input -` (stdin), with mutual exclusivity enforced by the parser.
- Error handling defaults to continue-on-error but supports `--stop-on-error` for immediate failure.
- Exit codes distinguish between complete success (0), partial failure (1), and success-with-warnings (2).
- The `--force` flag bypasses document protection checks for `.docx` files, while `--json` wraps results in a standardized envelope.

## Frequently Asked Questions

### What is the difference between resident and non-resident batch execution?

Resident execution sends the entire batch to a running OfficeCLI server process, which applies changes in-memory and defers disk writes. Non-resident execution opens the document once, sets `DeferSave = true`, and processes items sequentially before closing. The resident path offers better performance for multiple rapid operations, while the non-resident path ensures immediate persistence.

### How do I pass multiple commands to OfficeCLI batch mode?

Provide a JSON array where each object contains a `command` key (e.g., `add`, `set`, `remove`) and relevant parameters like `path`, `parent`, or `props`. Supply this array via `--commands` for inline JSON, `--input batch.json` for file input, or pipe via stdin using `--input -` according to the implementation in [`CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Batch.cs).

### What exit code does OfficeCLI return when a batch operation fails?

OfficeCLI returns exit code `1` when any batch item fails or when document protection blocks an operation. If all items succeed but warnings were generated (such as unrecognized LaTeX tokens), the exit code is `2`. A clean exit with code `0` indicates complete success with no warnings.

### How do I force OfficeCLI to bypass document protection in batch mode?

Add the `--force` flag to your batch command. This bypasses the document-level protection check that occurs for `.docx` files before mutations (lines 104-110 in [`CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Batch.cs)), mirroring the behavior of the standalone `set --force` command. Use this option with caution as it modifies protected documents.