| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Management.Automation; |
| | | 3 | | using Serilog.Events; |
| | | 4 | | |
| | | 5 | | namespace Kestrun.Languages; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Shared helper methods for configuring and invoking PowerShell scripts in a consistent manner. |
| | | 9 | | /// Extracted to reduce duplication between <see cref="PowerShellDelegateBuilder"/> and script-based probes. |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class PowerShellExecutionHelpers |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Sets variables in the PowerShell runspace from the provided argument dictionary. |
| | | 15 | | /// Existing variables are overwritten. Null or empty collections are ignored. |
| | | 16 | | /// </summary> |
| | | 17 | | internal static void SetVariables(PowerShell ps, IReadOnlyDictionary<string, object?>? arguments, Serilog.ILogger lo |
| | | 18 | | { |
| | 7 | 19 | | if (arguments is null || arguments.Count == 0) |
| | | 20 | | { |
| | 4 | 21 | | return; |
| | | 22 | | } |
| | | 23 | | |
| | 3 | 24 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 25 | | { |
| | 0 | 26 | | log.Verbose("Setting PowerShell variables from arguments: {Count}", arguments.Count); |
| | | 27 | | } |
| | 3 | 28 | | var proxy = ps.Runspace.SessionStateProxy; |
| | 18 | 29 | | foreach (var kv in arguments) |
| | | 30 | | { |
| | 6 | 31 | | proxy.SetVariable(kv.Key, kv.Value); |
| | | 32 | | } |
| | 3 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Adds a script block to the pipeline. |
| | | 37 | | /// </summary> |
| | 4 | 38 | | internal static void AddScript(PowerShell ps, string code) => _ = ps.AddScript(code); |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Adds a culture initialization prelude to the PowerShell pipeline. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="ps">The PowerShell instance to configure.</param> |
| | | 44 | | /// <param name="cultureName">The culture name to apply.</param> |
| | | 45 | | /// <param name="log">The logger instance.</param> |
| | | 46 | | internal static void AddCulturePrelude(PowerShell ps, string? cultureName, Serilog.ILogger log) |
| | | 47 | | { |
| | 0 | 48 | | if (string.IsNullOrWhiteSpace(cultureName)) |
| | | 49 | | { |
| | 0 | 50 | | return; |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | string normalized; |
| | | 54 | | try |
| | | 55 | | { |
| | 0 | 56 | | normalized = CultureInfo.GetCultureInfo(cultureName).Name; |
| | 0 | 57 | | } |
| | 0 | 58 | | catch (CultureNotFoundException) |
| | | 59 | | { |
| | 0 | 60 | | return; |
| | | 61 | | } |
| | | 62 | | |
| | 0 | 63 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 64 | | { |
| | 0 | 65 | | log.Verbose("Applying PowerShell culture: {Culture}", normalized); |
| | | 66 | | } |
| | | 67 | | |
| | 0 | 68 | | var escaped = normalized.Replace("'", "''", StringComparison.Ordinal); |
| | 0 | 69 | | var prelude = "$__krCulture = [System.Globalization.CultureInfo]::GetCultureInfo('" + escaped + "'); " + |
| | 0 | 70 | | "[System.Globalization.CultureInfo]::CurrentCulture = $__krCulture; " + |
| | 0 | 71 | | "[System.Globalization.CultureInfo]::CurrentUICulture = $__krCulture;"; |
| | 0 | 72 | | _ = ps.AddScript(prelude); |
| | 0 | 73 | | } |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Invokes the configured PowerShell pipeline asynchronously with cooperative cancellation. |
| | | 77 | | /// Cancellation attempts to stop the pipeline gracefully. |
| | | 78 | | /// </summary> |
| | | 79 | | internal static async Task<PSDataCollection<PSObject>> InvokeAsync(this PowerShell ps, Serilog.ILogger log, Cancella |
| | | 80 | | { |
| | 17 | 81 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 82 | | { |
| | 0 | 83 | | log.Verbose("Executing PowerShell script..."); |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | // If cancellation is already requested before the pipeline starts, do not invoke at all. |
| | | 87 | | // On some platforms/runtimes, calling Stop() before invocation begins is a no-op and |
| | | 88 | | // the pipeline may still start and run indefinitely. |
| | 17 | 89 | | ct.ThrowIfCancellationRequested(); |
| | | 90 | | |
| | 17 | 91 | | using var registration = ct.Register(static state => |
| | 17 | 92 | | { |
| | 3 | 93 | | var shell = (PowerShell)state!; |
| | 6 | 94 | | try { shell.Stop(); } catch { /* ignored */ } |
| | 20 | 95 | | }, ps); |
| | | 96 | | |
| | | 97 | | try |
| | | 98 | | { |
| | 17 | 99 | | var invokeTask = ps.InvokeAsync(); |
| | | 100 | | |
| | | 101 | | // If cancellation is requested during the short window between registration and invocation, |
| | | 102 | | // attempt to stop immediately. |
| | 17 | 103 | | if (ct.IsCancellationRequested) |
| | | 104 | | { |
| | 2 | 105 | | try { ps.Stop(); } catch { /* ignored */ } |
| | | 106 | | } |
| | | 107 | | |
| | 17 | 108 | | var results = await invokeTask.ConfigureAwait(false); |
| | | 109 | | |
| | 14 | 110 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 111 | | { |
| | 0 | 112 | | log.Verbose("PowerShell script executed with {Count} results.", results.Count); |
| | | 113 | | } |
| | 14 | 114 | | return results; |
| | | 115 | | } |
| | 3 | 116 | | catch (PipelineStoppedException) when (ct.IsCancellationRequested) |
| | | 117 | | { |
| | | 118 | | // Convert PipelineStoppedException to OperationCanceledException when cancellation was requested |
| | 3 | 119 | | throw new OperationCanceledException("PowerShell pipeline was stopped due to cancellation.", ct); |
| | | 120 | | } |
| | 14 | 121 | | } |
| | | 122 | | } |