CliInvoke 3.2.0
Prefix Reserveddotnet add package CliInvoke --version 3.2.0
NuGet\Install-Package CliInvoke -Version 3.2.0
<PackageReference Include="CliInvoke" Version="3.2.0" />
<PackageVersion Include="CliInvoke" Version="3.2.0" />
<PackageReference Include="CliInvoke" />
paket add CliInvoke --version 3.2.0
#r "nuget: CliInvoke, 3.2.0"
#:package CliInvoke@3.2.0
#addin nuget:?package=CliInvoke&version=3.2.0
#tool nuget:?package=CliInvoke&version=3.2.0
CliInvoke
<img src="https://github.com/alastairlundy/CliInvoke/blob/main/.assets/icon.png" width="192" height="192" alt="CliInvoke Logo">
CliInvoke runs external processes from C# without the System.Diagnostics.Process footguns.
- Capture standard output and error in buffered mode without the classic stream deadlocks.
- Enforce timeouts and cancellation, with the process killed when a timeout fires.
- Unit-test your process-calling code by mocking
IProcessInvokerfromCliInvoke.Coreinstead of spawning real processes.
Table of Contents
- Features
- Comparison vs Alternatives
- Installing CliInvoke
- Examples
- Middleware
- Resource Disposal
- Documentation
- Contributing to CliInvoke
- License
- Acknowledgements
Features
- Launch guardrails: the Windows command-line length check catches the ~32,767 character
CreateProcesslimit before the process starts, instead of failing later with Win32 error 206. - Mockable design: reference
CliInvoke.Coreabstractions in your libraries and mockIProcessInvokerin unit tests. - A middleware pipeline for logging, retries, output truncation, and post-exit validation; PowerShell and CMD specializations via
UsePowerShellandUseCmd<sup>1</sup> - Dependency Injection extensions register
IProcessInvoker,IExternalProcessFactory, and middleware from a singleAddCliInvoke()call. - Supports AOT compilation and trimming, few dependencies, and SourceLink support. Supports .NET 10 and .NET 11.
<sup>1</sup> Specializations library distributed separately.
Comparison vs Alternatives
CliInvoke is compared against CliWrap, ProcessX, and the built-in .NET Process class across features like configuration separation, DI support, middleware, cross-platform support, and licensing.
See the full comparison table for a detailed feature-by-feature breakdown.
Choose CliInvoke when DI integration, middleware, and mockable abstractions matter. If CliWrap's streaming API fits your project and you don't need those, it remains a solid choice.
Installing CliInvoke
CliInvoke is available on the NuGet Gallery but can also be installed via the dotnet SDK CLI.
The package(s) to install depends on your use case:
- For use in a .NET library – Install the abstractions package. Your developer users can install the Implementation and Dependency Injection packages.
- For use in a .NET app – Install the implementation package. It includes DI registration and convenience helpers built in.
| Project type / Need | Packages to install (dotnet add package ...) | Notes |
|---|---|---|
| Library author (provide abstractions only) | CliInvoke.Core |
Only the Core (abstractions) package. Consumers can choose implementations. |
| Library or app that needs concrete builders / implementations | CliInvoke.Core, CliInvoke |
Implementation package plus Core for models/abstractions. |
| Desktop or Console application (common case, use DI & convenience helpers) | CliInvoke.Core, CliInvoke |
Includes DI registration and convenience helpers; some Middleware implementations are built into the main package. |
| Any project that needs platform‑specific or shell specializations (optional) | CliInvoke.Specializations (install in addition to the packages above as needed) |
Adds Cmd/PowerShell and other specializations; include only when required. |
Links to packages
CliInvoke.Core Nuget CliInvoke Nuget CliInvoke.Specializations Nuget
Supported Platforms
CliInvoke supports Windows, macOS, Linux, FreeBSD, and Android (untested). Note: the PowerShell middleware does not support Android. Shell specializations via UsePowerShell are unavailable there.
CliInvoke targets .NET 10 and .NET 11 only, by design. .NET 8 and .NET 9 leave Microsoft support in November 2026, and supporting netstandard2.0 in v2 added real maintenance cost. The 2.x release line, which supports older runtimes, is itself unsupported after December 1, 2026.
For more details see the list of supported platforms
Design Patterns & When to Use Them
CliInvoke provides three core design patterns for invoking processes (with DI + Middleware and the platform Specializations as composition paths). See DESIGN_PATTERNS.md for comprehensive documentation on each pattern, including a Which pattern should I use? decision tree and a Configuration Patterns guide.
CliRun, recommended default. Beginner-friendly entrypoint for basic scripting, CI/CD tasks, or simple command execution. Zero boilerplate, optional arguments with sensible defaults. Start here if you are new to CliInvoke.IProcessInvoker, DI-centric pattern for end-to-end process management. Use when building applications that need testability, dependency injection integration, or custom process configuration per invocation.IExternalProcess&IExternalProcessFactory, process-like API with DI support. Use when you need granular lifecycle control, manual start/stop sequences, or power-user scenarios similar toSystem.Diagnostics.Process.
New to CliInvoke? Start with
CliRun. It is the recommended default entry point. Reach forIProcessInvokerwhen you need DI or middleware, andIExternalProcesswhen you need process-level control.
Examples
Beginner Friendly / Quickstart
For simple use cases, the CliRun helper provides a straightforward API to execute commands with minimal boilerplate:
using CliInvoke;
using CliInvoke.Core;
// Execute a command and get the result
ProcessResult result = await CliRun.RunAsync("dotnet", "--version");
Console.WriteLine($"Exit Code: {result.ExitCode}");
For capturing output, use RunBufferedAsync:
using CliInvoke;
using CliInvoke.Core;
// Execute and capture stdout/stderr
BufferedProcessResult result = await CliRun.RunBufferedAsync("dotnet", "--info");
Console.WriteLine(result.StandardOutput);
Console.WriteLine(result.StandardError);
CliRun is ideal for scripting, quick prototypes, and basic command execution where you don't need dependency injection or advanced configuration.
For detailed documentation on all available patterns and when to use them, see DESIGN_PATTERNS.md.
Advanced Configuration
For fine-grained control over process execution, such as custom timeouts, cancellation strategies, buffered vs. non-buffered output, and builder-based configuration, see the Configuration Guide and the Choosing your Invocation Pattern guide in the documentation portal.
Most configurations are built with direct init construction (see Configuration Patterns). The builder path is for argument escaping, user credentials, and resource policy features.
Child output is decoded as UTF-8 by default. Legacy Windows tools that emit OEM or ANSI code-page text need their encodings set explicitly, through the StandardOutputEncoding/StandardErrorEncoding init properties or the builder's SetEncoding method, or captured output comes back as mojibake. See the troubleshooting guide.
Choosing between Arguments and ArgumentList
ProcessConfiguration accepts command-line arguments in two ways:
Argumentsis a preformatted command-line string. CliInvoke passes it to the process (or to a shell composition) exactly as written. It does not keep the values inside it separate: any delimiter the consuming shell recognises, a space on the POSIX path, splits the text into separate arguments. Quoting and escaping inside this string are the caller's responsibility.ArgumentListholds one value per entry, for example a single file name. Each entry is delivered to the target as exactly one argument, quoted or escaped per shell by the library. This is the form to use when a value must arrive unchanged, whatever characters it contains.
When ArgumentList is non-empty it takes precedence over Arguments.
Example. A caller wants safe.txt --overwrite to arrive as one file name. Passing it as
a single ArgumentList entry does that. Passing the same text in Arguments does not; the
shell splits it at the space:
Argument count: 2
argv[1] = <safe.txt>
argv[2] = <--overwrite>
(The expected result for a single-argument call is Argument count: 1,
argv[1] = <safe.txt --overwrite>.)
Migration one-liner: a single value currently placed in Arguments belongs in ArgumentList
as one entry.
Middleware
CliInvoke's ProcessInvoker supports an optional middleware system that lets you plug cross-cutting concerns, such as logging, validation, platform selection, and retries, around the process pipeline without changing how you call it. Middleware wraps the terminal pipeline in the order you register, and call sites (ExecuteAsync, ExecuteBufferedAsync) remain identical.
Built-in middleware includes UseLogging, UsePostExitValidation, UsePowerShell, and UseCmd. Middleware can be configured by hand or through DI via the IProcessMiddlewareBuilder callback in AddCliInvoke. UsePowerShell/UseCmd also require registering the Specializations middleware types via AddCliInvokeSpecializations() from the CliInvoke.Specializations package. See that package's README.
For the full guide, constructor details, the IProcessMiddleware contract, DI configuration, result ownership, and the result-swap rule, see the Middleware Guide.
Runners are identified by file name. Invoke shell runners by their canonical names (cmd.exe, pwsh/powershell); a renamed shell binary is treated as an ordinary target and receives tokenized delivery, and shell-specific composition and its validation do not apply.
Resource Disposal
CliInvoke has four Resource-Owning Types that implement IDisposable and must be disposed after use to avoid resource leaks (open pipe handles, kernel handles, and pinned SecureString buffers):
| # | Type | What it owns |
|---|---|---|
| 1 | IExternalProcess |
Underlying System.Diagnostics.Process (pipes, handles, threads) |
| 2 | UserCredential |
SecureString password buffer |
| 3 | UserCredentialSpec |
SecureString password buffer staged for Build() |
| 4 | ProcessConfigurationBuilder |
The UserCredentialSpec it created. Dispose() disposes only that spec (and its staged SecureString), never caller-supplied Credential/StandardInput |
Always wrap these four types in using or await using statements.
For ProcessConfigurationBuilder, the user remains responsible for disposing any Credential and StandardInput they supply to it. The builder does not dispose caller-provided credential/stdin resources.
ProcessConfiguration is a plain immutable value object and does not implement IDisposable. The StandardInput (StreamWriter) and UserCredential you place inside it remain your responsibility to dispose. CliInvoke never disposes them on your behalf.
For the full disposal reference, ownership rules, disposal patterns, and a checklist, see the Resource Disposal Guide.
Middleware does not change these rules. A middleware chain returns the process result un-disposed to the caller, so the disposal contract described above applies exactly as it does without middleware. See Middleware for the result-ownership note.
Documentation
Full documentation is available in the CliInvoke Developer Site. Pick the path that fits you:
| Who you are | Start here |
|---|---|
| Beginner, "I just need to run a command" | Quickstart → Choosing your Invocation Pattern |
| Professional Developer, "I'm building a testable app with DI" | Getting Started → Configuration |
| Power User, "I need full lifecycle control" | Choosing your Invocation Pattern → IExternalProcess → Architecture |
Other guides: Troubleshooting, Migration Guides, Building from Source
How to Build CliInvoke's code
Please see building-cliinvoke.md for how to build CliInvoke from source.
How to Contribute to CliInvoke
Please see the CONTRIBUTING.md file for code and localisation contributions.
If you want to file a bug report or suggest a potential feature to add, please check out the GitHub issues page to see if a similar or identical issue is already open. If there isn't already a relevant issue filed, please file one here and follow the respective guidance from the appropriate issue template.
License
CliInvoke is licensed under the MPL 2.0 license. You can learn more about it here
Should your project incorporate CliInvoke, ensure that the full text of CliInvoke's LICENSE.txt is either incorporated into your third-party licenses TXT file or provided as a distinct TXT file within your project's repository.
CliInvoke Assets
The CliInvoke icon is a separately-owned asset and is not licensed under MPL-2.0 like the rest of the codebase.
If you fork CliInvoke and re-distribute it, please replace the icon with your own artwork
unless you have written permission from the maintainer. To request permission, open a
GitHub issue tagged asset-license.
Star History
<a href="https://www.star-history.com/?repos=alastairlundy%2Fcliinvoke&type=date&logscale=&legend=top-left"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=alastairlundy/cliinvoke&type=date&theme=dark&logscale&legend=top-left&sealed_token=h1uzYyzJYAg46ZWXSuf2_bPDCJnRasjV-VB06DK8CRLmjAXg8727LKwfi76Hu7ksNmIpIUD8RXHTquovJuQcCFlnkXAOjYaMjCA5J_I4GHXl3HhXtWrH_wrFMhjP0Ih3lM0Lybq8d8MZiVK86dyS2LnL3b90dirCckN1UvaDX6fggyHlB7y-E61gb6Fz" /> <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=alastairlundy/cliinvoke&type=date&logscale&legend=top-left&sealed_token=h1uzYyzJYAg46ZWXSuf2_bPDCJnRasjV-VB06DK8CRLmjAXg8727LKwfi76Hu7ksNmIpIUD8RXHTquovJuQcCFlnkXAOjYaMjCA5J_I4GHXl3HhXtWrH_wrFMhjP0Ih3lM0Lybq8d8MZiVK86dyS2LnL3b90dirCckN1UvaDX6fggyHlB7y-E61gb6Fz" /> <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=alastairlundy/cliinvoke&type=date&logscale&legend=top-left&sealed_token=h1uzYyzJYAg46ZWXSuf2_bPDCJnRasjV-VB06DK8CRLmjAXg8727LKwfi76Hu7ksNmIpIUD8RXHTquovJuQcCFlnkXAOjYaMjCA5J_I4GHXl3HhXtWrH_wrFMhjP0Ih3lM0Lybq8d8MZiVK86dyS2LnL3b90dirCckN1UvaDX6fggyHlB7y-E61gb6Fz" /> </picture> </a>
Acknowledgements
Projects
Thanks to these projects:
For more information, please see the THIRD_PARTY_NOTICES file.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- CliInvoke.Core (>= 3.2.0)
- Microsoft.Extensions.Caching.Memory (>= 11.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 11.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 11.0.0)
-
net11.0
- CliInvoke.Core (>= 3.2.0)
- Microsoft.Extensions.Caching.Memory (>= 11.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on CliInvoke:
| Package | Downloads |
|---|---|
|
CliInvoke.Specializations
Shell middleware for CliInvoke. Run commands through PowerShell, CMD, or the user's default shell with UsePowerShell, UseCmd, and UseDefaultShell. Requires the CliInvoke package. |
|
|
CliInvoke.Extensions
Adds a ``AddCliInvoke`` Dependency Injection extension method to enable easy CliInvoke setup when using the Microsoft.Extensions.DependencyInjection package. |
GitHub repositories
This package is not used by any popular GitHub repositories.
## Changes since 3.1
CliInvoke 3.2.0 adds .NET 11 support and new exceptions that report child-process details when timeouts or cancellations occur. It also fixes process startup, shutdown, retry, and validation edge cases - Several of these have been backported to 3.1.x via 3.1.3
### Added
- All three packages, `CliInvoke.Core`, `CliInvoke`, and `CliInvoke.Specializations`, now ship assets for .NET 10 and .NET 11. Source builds require the .NET 10 and .NET 11 SDKs, and `global.json` pins version 11.0.100.
- The new exceptions `CliInvokeTimeoutException` and `CliInvokeCanceledException` carry `ProcessId`, `Elapsed`, and a `ChildState` snapshot when the exit configuration allows cancellation exceptions to propagate. `ProcessDiagnostic` records the child's exit state, exit code, suspension state, elapsed time, and capture time. Both exception types derive from `OperationCanceledException`, so existing handlers still catch them. The original cancellation token remains available. `CliInvokeTimeoutException` does not derive from `TimeoutException`.
### Performance
- Buffered output capture now uses less memory. It avoids extra copies before decoding text and reuses transfer buffers. The captured text remains unchanged.
- Validation rules and environment-variable comparisons also use less memory. `RequiresExitCodeZero` reuses the same function instead of creating a new one each time. `ProcessConfiguration.Equals` compares environment variables by key instead of comparing sorted lists.
### Fixed
- Raw-mode invocations no longer deadlock when a child writes enough output to fill an unread pipe.
- Buffered cancellation now behaves consistently when `CancellationThrowsException` is `false`. Cancellation while reading captured output returns a `BufferedProcessResult` with `Canceled` set to `true` and empty output. When the option is `true`, cancellation exceptions propagate.
- Timer-driven timeouts now use the same clock as the process kill timer. This prevents a timeout from being reported as a caller cancellation or as an uncanceled result.
- The standard wait path now waits for the operating system to confirm process exit after a forceful process kill.
- Resource-policy setters tolerate children that exit while CliInvoke applies the policy. Resume handling also uses the held process handle and terminates a child if its initial resume fails.
- Non-shell child processes on .NET 11 start suspended on Windows and macOS so CliInvoke can apply `ProcessResourcePolicy` before the child runs. Linux and FreeBSD keep their existing start behavior.
- Retry middleware rewinds seekable standard input before each retry. A non-seekable input stream now throws `InvalidOperationException` when a retry is about to run instead of sending an empty stream.
- `LoggingMiddleware` logs `ArgumentList` when the argument string is empty. The display value still passes through the configured sanitizer.
- `ProcessResult.Signal` now converts native Unix signal numbers through the platform mapping on .NET 11.
- `AllowExceptionsIfUnexpected` no longer swallows non-cancellation failures that happen near a timeout.
### Changed
- `CliInvoke` now references Microsoft.Extensions.DependencyInjection.Abstractions, Microsoft.Extensions.Logging.Abstractions, and Microsoft.Extensions.Caching.Memory 11.0.0.
- `CliInvoke` no longer depends on DotExtensions. The path and version helpers now live in the repository.
- Polyfill moved from `CliInvoke.Core` to `CliInvoke` and now uses version 12.0.0. The `CliInvoke` package also uses Squash for build-time trimming.
- Argument exceptions in configuration and policy methods now include the offending parameter name.