| | | 1 | | using System.Management.Automation; |
| | | 2 | | namespace Kestrun.Utilities; |
| | | 3 | | |
| | | 4 | | /// <summary> |
| | | 5 | | /// Utilities for invoking PowerShell with cancellation support. |
| | | 6 | | /// </summary> |
| | | 7 | | internal static class PowerShellInvokeExtensions |
| | | 8 | | { |
| | | 9 | | /// <summary> |
| | | 10 | | /// Invokes a PowerShell instance asynchronously, supporting cancellation via a CancellationToken. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <param name="ps">The PowerShell instance to invoke.</param> |
| | | 13 | | /// <param name="requestAborted">The CancellationToken to observe for cancellation.</param> |
| | | 14 | | /// <param name="onAbortLog">Optional action to log when an abort is requested.</param> |
| | | 15 | | /// <returns>A task representing the asynchronous operation, with the PowerShell results.</returns> |
| | | 16 | | public static async Task<PSDataCollection<PSObject>> InvokeWithRequestAbortAsync( |
| | | 17 | | this PowerShell ps, |
| | | 18 | | CancellationToken requestAborted, |
| | | 19 | | Action? onAbortLog = null) |
| | | 20 | | { |
| | 11 | 21 | | requestAborted.ThrowIfCancellationRequested(); |
| | | 22 | | |
| | | 23 | | // If the request aborts, stop the PS pipeline. |
| | 11 | 24 | | using var reg = requestAborted.Register(() => |
| | 11 | 25 | | { |
| | 11 | 26 | | try |
| | 11 | 27 | | { |
| | 0 | 28 | | onAbortLog?.Invoke(); |
| | 11 | 29 | | |
| | 11 | 30 | | // Stop is the canonical cancellation mechanism for hosted PS. |
| | 11 | 31 | | // Safe to call even if invocation hasn't started yet. |
| | 0 | 32 | | ps.Stop(); |
| | 0 | 33 | | } |
| | 0 | 34 | | catch |
| | 11 | 35 | | { |
| | 11 | 36 | | // Intentionally swallow: abort paths must be "best effort" |
| | 0 | 37 | | } |
| | 11 | 38 | | }); |
| | | 39 | | |
| | | 40 | | try |
| | | 41 | | { |
| | | 42 | | // Your current style |
| | 11 | 43 | | return await ps.InvokeAsync().ConfigureAwait(false); |
| | | 44 | | } |
| | 0 | 45 | | catch (PipelineStoppedException) when (requestAborted.IsCancellationRequested) |
| | | 46 | | { |
| | | 47 | | // Treat as cancellation, not an error. |
| | 0 | 48 | | throw new OperationCanceledException(requestAborted); |
| | | 49 | | } |
| | 11 | 50 | | } |
| | | 51 | | } |