| | | 1 | | using System.Management.Automation; |
| | | 2 | | using Serilog.Events; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.Languages; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Shared helper methods for configuring and invoking PowerShell scripts in a consistent manner. |
| | | 8 | | /// Extracted to reduce duplication between <see cref="PowerShellDelegateBuilder"/> and script-based probes. |
| | | 9 | | /// </summary> |
| | | 10 | | internal static class PowerShellExecutionHelpers |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Sets variables in the PowerShell runspace from the provided argument dictionary. |
| | | 14 | | /// Existing variables are overwritten. Null or empty collections are ignored. |
| | | 15 | | /// </summary> |
| | | 16 | | internal static void SetVariables(PowerShell ps, IReadOnlyDictionary<string, object?>? arguments, Serilog.ILogger lo |
| | | 17 | | { |
| | 8 | 18 | | if (arguments is null || arguments.Count == 0) |
| | | 19 | | { |
| | 4 | 20 | | return; |
| | | 21 | | } |
| | | 22 | | |
| | 4 | 23 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 24 | | { |
| | 0 | 25 | | log.Verbose("Setting PowerShell variables from arguments: {Count}", arguments.Count); |
| | | 26 | | } |
| | 4 | 27 | | var proxy = ps.Runspace!.SessionStateProxy; |
| | 24 | 28 | | foreach (var kv in arguments) |
| | | 29 | | { |
| | 8 | 30 | | proxy.SetVariable(kv.Key, kv.Value); |
| | | 31 | | } |
| | 4 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Adds a script block to the pipeline. |
| | | 36 | | /// </summary> |
| | 4 | 37 | | internal static void AddScript(PowerShell ps, string code) => _ = ps.AddScript(code); |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Invokes the configured PowerShell pipeline asynchronously with cooperative cancellation. |
| | | 41 | | /// Cancellation attempts to stop the pipeline gracefully. |
| | | 42 | | /// </summary> |
| | | 43 | | internal static async Task<PSDataCollection<PSObject>> InvokeAsync(PowerShell ps, Serilog.ILogger log, CancellationT |
| | | 44 | | { |
| | 4 | 45 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 46 | | { |
| | 0 | 47 | | log.Verbose("Executing PowerShell script..."); |
| | | 48 | | } |
| | | 49 | | |
| | 4 | 50 | | using var registration = ct.Register(static state => |
| | 4 | 51 | | { |
| | 0 | 52 | | var shell = (PowerShell)state!; |
| | 0 | 53 | | try { shell.Stop(); } catch { /* ignored */ } |
| | 4 | 54 | | }, ps); |
| | | 55 | | |
| | 4 | 56 | | var results = await ps.InvokeAsync().ConfigureAwait(false); |
| | | 57 | | |
| | 4 | 58 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | | 59 | | { |
| | 0 | 60 | | log.Verbose("PowerShell script executed with {Count} results.", results.Count); |
| | | 61 | | } |
| | 4 | 62 | | return results; |
| | 4 | 63 | | } |
| | | 64 | | } |