# Scripting patterns

> Shell, PowerShell, and CI scripting patterns for UiPath CLI, built on the exit-code and JSON-envelope contracts.

This page collects the patterns that make `uip` easy to script against — in shell, PowerShell, and CI pipelines. Nothing here is specific to a single tool; every pattern builds on the contract that the [exit code](./exit-codes.md) and [JSON envelope](./output-formats.md) expose consistently across commands.

## Helpful defaults

Three design decisions make scripting straightforward:

1. **JSON is the default output.** No `--output json` needed, whether you are in a terminal or a pipeline.
2. **Stdout is JSON only; everything else is stderr.** Logs, progress bars, and human-readable error text go to stderr, so capturing stdout gives you clean data.
3. **Exit codes are narrow and stable.** Five values (`0`, `1`, `2`, `3`, `4`) cover every documented failure mode, plus `130` for user cancellation. Scripts can branch without parsing strings.

## Strict shell options

For bash / zsh, start scripts with:

```bash
#!/usr/bin/env bash
set -euo pipefail
```

- `-e` — abort on any command that exits non-zero.
- `-u` — abort on an undefined variable.
- `-o pipefail` — propagate a failure from any stage of a pipeline, not just the last one.

For PowerShell:

```powershell
$ErrorActionPreference = 'Stop'
```

## Branching on exit codes

The `Result` value on the envelope maps one-to-one to the process exit code. Branch on the exit code for fast decisions; open the envelope for detail (see [Exit codes](./exit-codes.md) for the full table).

```bash
if uip or folders list --limit 50 --output-filter "[?Name=='Shared'] | [0]" > shared.json; then
  echo "Shared folder found"
else
  case $? in
    2)  echo "re-authenticating"; uip login --client-id env.UIPATH_CLIENT_ID --client-secret env.UIPATH_CLIENT_SECRET --tenant "$UIPATH_TENANT" ;;
    3)  echo "bad flag — aborting"; exit 3 ;;
    *)  echo "unexpected failure"; exit 1 ;;
  esac
fi
```

## Reading values out of the envelope

Use `--output-filter` (JMESPath) to extract values at the source, rather than piping through `jq`:

```bash
FOLDER_KEY=$(uip or folders list --limit 50 --all --name Shared --output-filter "[0].Key" --output plain)
```

`--output plain` returns the bare value (no quotes) for a scalar filter result. For arrays and objects, `--output json` keeps the structure:

```bash
PROCESS_KEYS=$(uip or processes list --limit 50 --folder-path Shared --output-filter "[*].Key")
echo "$PROCESS_KEYS" | jq -r '.[]' | while read -r key; do
  uip or jobs start "$key"
done
```

If you prefer `jq` end-to-end, capture raw JSON and chain:

```bash
FOLDER_KEY=$(uip or folders list --all --name Shared | jq -r '.Data[0].Key')
```

Both approaches produce the same value. `--output-filter` is faster and validates at CLI-parse time; `jq` gives you the full JMESPath **plus** jq-specific constructs like `[-1]` (last element) and `to_entries`.

## Calling an endpoint that no command covers

When a script needs a UiPath REST endpoint that no `uip` command covers, call it with [`uip api`](./uip-api.md). The CLI adds the base URL, the organization, the tenant, and the access token, so the script does not handle the token:

```bash
uip api 'orchestrator_/odata/Folders?$top=5' --output-filter "Body.value[*].DisplayName"
```

A failed response exits with the same codes as any other command, and the envelope carries the service's response in `Data`.

## Re-authenticating on AuthenticationError (exit 2)

Access tokens expire. In a long-running script, the pattern is: run the command, fall back to `uip login` if the token is gone, retry once, then fail hard.

```bash
uip_retry() {
  uip "$@" && return 0
  local code=$?
  if [[ $code -eq 2 ]]; then
    uip login \
      --client-id env.UIPATH_CLIENT_ID \
      --client-secret env.UIPATH_CLIENT_SECRET \
      --tenant "$UIPATH_TENANT" >/dev/null
    uip "$@"
  else
    return $code
  fi
}

uip_retry or folders list --all
```

Keep retries bounded — a single auth retry handles token expiry; further retries would mask a misconfigured credential and burn rate limits.

## Branching on ErrorCode and Retry

Every failure envelope also carries `ErrorCode` (a stable taxonomy like `rate_limited`, `network_error`, `not_found`) and `Retry` (`RetryWillNotFix`, `RetryLater`, `RetryAfter1Second`, …) — see [Output formats — the envelope](./output-formats.md#the-envelope). These are populated automatically even when a command doesn't set them explicitly, and they're finer-grained than the exit code alone: exit `1` alone doesn't tell you whether a `not_found` and a `rate_limited` failure both mapped to it are worth retrying.

```bash
if ! uip or folders list --output json > folders.json; then
  RETRY=$(jq -r '.Retry // empty' folders.json 2>/dev/null)
  case "$RETRY" in
    RetryLater|RetryAfter*) sleep 5; uip or folders list --output json > folders.json ;;
    RetryWillNotFix|"") exit 1 ;;
  esac
fi
```

Prefer branching on `Retry` over parsing `ErrorCode` string-by-string when all you need is "should I try again" — it's the field designed for exactly that decision.

## Polling long-running operations

Some operations complete asynchronously on the Orchestrator side:

- Job execution — use `uip or jobs start --wait-for-completion` to have the CLI poll for you. Default timeout is 300 seconds, adjustable with `--timeout`. Poll interval is 5 seconds, adjustable with `--poll-interval`.
- Solution deployment — `uip solution deploy run` polls internally with a default timeout of 360 seconds.
- Test execution — `uip tm testsets run` **launches** the run, returns an `ExecutionId`, and exits immediately with `0`. To block until the run completes, chain `uip tm wait` (which polls, exits `1` when a test failed or the run was cancelled, and exits `4` on timeout). To read the counts after waiting, inspect `Data.Failed` in `uip tm report get`. See [uip tm testsets](./uip-test-manager-testsets.md), [uip tm executions](./uip-test-manager-executions.md), and [uip tm wait](./uip-test-manager-wait.md).

When the built-in polling is too coarse, or when the terminal state needs custom handling, poll yourself:

```bash
JOB_KEY=$(uip or jobs start "$PROCESS_KEY" --output-filter "Jobs[0].Key" --output plain)

while :; do
  STATE=$(uip or jobs get "$JOB_KEY" --output-filter "State" --output plain)
  case "$STATE" in
    Successful) echo "done"; break ;;
    Faulted|Stopped) echo "job $STATE"; exit 1 ;;
    *) sleep 10 ;;
  esac
done
```

Always cap the loop on time — a Faulted job that ends up in a Pending loop will otherwise block forever:

```bash
DEADLINE=$(( SECONDS + 1800 ))
while (( SECONDS < DEADLINE )); do
  # … as above …
done
[[ $SECONDS -ge $DEADLINE ]] && { echo "timed out"; exit 1; }
```

## Idempotent pipelines

Many `uip` commands are idempotent by design — re-running them with the same arguments either returns the existing resource or does nothing:

- `uip solution publish` — re-publishing a package with the same name and version returns the existing version.
- `uip tools install` — a no-op if the tool is already installed.
- `uip or processes create` — will fail on duplicate name-in-folder; use `uip or processes update-version` or `uip or processes edit` in that case.

`uip or assets create` is **not** idempotent — it fails on a duplicate name-in-folder, and there is no one-shot upsert flag. For a re-runnable deploy loop, list first and branch to `create` or `update` per row — see [How-to: manage Orchestrator resources — bulk-deploy assets](./howto-manage-resources.md#bulk-deploy-assets-from-a-csv).

Combine these with `set -e` to build pipelines that are safe to re-run after a partial failure without cleanup steps.

## Separating data from logs

Stdout is JSON. Stderr is everything else. Redirect them independently:

```bash
uip or folders list > folders.json 2> uip.log
```

This is especially important in CI: a job that prints progress indicators or `npm` output inline with the data stream will produce mangled JSON for later steps to consume.

## Handling empty results

A command that succeeds with zero rows in `Data` exits `0` — the list query worked, but nothing matched. Detect this with `--output-filter`:

```bash
COUNT=$(uip or folders list --limit 50 --all --name DoesNotExist --output-filter "length(@)" --output plain)
if [[ "$COUNT" -eq 0 ]]; then
  echo "no match"
  exit 1
fi
```

Do **not** pattern-match on the absence of a `Name` in the table output; it is not a parseable format.

## Pinning versions in CI

Reproducible pipelines require a freeze. `npm install -g @uipath/cli@<version>` alone does not hold the CLI at that version, and tools install at the newest patch on the CLI line. A freeze is a `versions` block in `.uipath/config.json`, committed to the repository. It pins the CLI, each tool, and the skills.

Write the freeze once, on a machine with the chosen CLI installed, from the repository root:

```bash
npm install -g @uipath/cli@<version>
mkdir -p .uipath && touch .uipath/config.json   # only when the repo has no config file
uip config freeze --all                         # pins the CLI, every tool and the skills
git add .uipath/config.json
```

In every pipeline job that runs `uip`, run these commands from the repository root:

```bash
CLI_PIN=$(node -p "require('./.uipath/config.json').versions.cli") || exit 1
npm install -g "@uipath/cli@$CLI_PIN"
uip update
```

See [Freezing a CI pipeline](./versioning.md#freezing-a-ci-pipeline) for the details.

## Suppressing interactive prompts

A handful of `uip` commands are interactive by default when stdout is a TTY:

- `uip login` — prompts for tenant selection if `--tenant` is not passed.
- `uip skills install/update/uninstall` — prompts for the target agent if `--agent` is not passed.
- `uip completion` — prompts to confirm the install path.
- `uip tools search` — prompts for a query if none is passed.

In CI these prompts can hang a job. Avoid them by always passing the relevant flags (`--tenant`, `--agent`, `--print`/explicit shell on `completion`) or by ensuring stdout is not a TTY (most CI runners already take care of this).

## Disabling telemetry in CI

Anonymous telemetry is sent to UiPath's Application Insights by default. For air-gapped or strict environments:

```bash
export UIPATH_TELEMETRY_DISABLED=1
```

…or point it at your own instance via `UIPATH_AI_CONNECTION_STRING`. See [Installing UiPath CLI — Telemetry](./installing-uipath-cli.md#telemetry).

## See also

- [Exit codes](./exit-codes.md) — the authoritative table.
- [Output formats](./output-formats.md) — the envelope and the five formats.
- [Global options](./global-options.md) — `--output`, `--output-filter`, `--log-level`, `--log-file`.
- [Authentication](./authentication.md) — the auth flows referenced in the retry pattern above.
- [CI/CD recipes](./recipes-azure-devops.md) — complete platform-specific pipelines.
