Modules/Private/40-Execution.ps1

function Invoke-RangerRetry {
    param(
        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock,

        [int]$RetryCount = 2,
        [int]$DelaySeconds = 1,
        [string]$Label = 'operation',
        [string]$Target,
        [string[]]$RetryOnExceptionType = @(),
        [switch]$Exponential,

        # Issue #172: optional scriptblock called with $_ to decide whether to retry.
        # Return $true to retry, $false to rethrow immediately without waiting.
        # Takes precedence over RetryOnExceptionType when provided.
        [scriptblock]$ShouldRetry
    )

    $attempt = 0
    do {
        try {
            return & $ScriptBlock
        }
        catch {
            $attempt++
            $exceptionType = if ($_.Exception) { $_.Exception.GetType().FullName } else { 'UnknownException' }

            $shouldRetryThis = if ($ShouldRetry) {
                try { [bool](& $ShouldRetry $_) } catch { $true }
            } elseif ($RetryOnExceptionType.Count -gt 0) {
                $exceptionType -in $RetryOnExceptionType
            } else {
                $true
            }

            if (-not $shouldRetryThis -or $attempt -gt $RetryCount) {
                throw
            }

            $delay = if ($Exponential) { [math]::Pow(2, $attempt - 1) * $DelaySeconds } else { $DelaySeconds }
            Write-RangerLog -Level debug -Message "Retry attempt $attempt/$RetryCount for '$Label'$(if ($Target) { " on '$Target'" }) after ${exceptionType}: $($_.Exception.Message)"
            Add-RangerRetryDetail -Target $Target -Label $Label -Attempt $attempt -ExceptionType $exceptionType -Message $_.Exception.Message
            Start-Sleep -Seconds $delay
        }
    } while ($true)
}

function Get-RangerWinRmProbeCacheKey {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ComputerName
    )

    # Issue #158: cache key is target-only — Test-WSMan probes connectivity (port + WinRM service
    # reachability), not credential authorization. Keying on credential caused one probe per
    # candidate, redundant re-probes, and misleading "preflight succeeded" log lines immediately
    # before "Access is denied" errors.
    return $ComputerName.Trim().ToLowerInvariant()
}

function Test-RangerWinRmTarget {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ComputerName,

        [PSCredential]$Credential
    )

    if (-not $script:RangerWinRmProbeCache) {
        $script:RangerWinRmProbeCache = @{}
    }

    $cacheKey = Get-RangerWinRmProbeCacheKey -ComputerName $ComputerName
    if ($script:RangerWinRmProbeCache.ContainsKey($cacheKey)) {
        return $script:RangerWinRmProbeCache[$cacheKey]
    }

    $probeMessages = New-Object System.Collections.Generic.List[string]
    $probeOptions = @(
        [ordered]@{ transport = 'http';  port = 5985; useSsl = $false },
        [ordered]@{ transport = 'https'; port = 5986; useSsl = $true }
    )

    foreach ($probe in $probeOptions) {
        $portReachable = $true
        if (Test-RangerCommandAvailable -Name 'Test-NetConnection') {
            try {
                $connection = Test-NetConnection -ComputerName $ComputerName -Port $probe.port -WarningAction SilentlyContinue
                $portReachable = [bool]$connection.TcpTestSucceeded
            }
            catch {
                $portReachable = $false
            }

            if (-not $portReachable) {
                $probeMessages.Add("TCP $($probe.port) unreachable")
                continue
            }
        }

        if (Test-RangerCommandAvailable -Name 'Test-WSMan') {
            # Issue #158: do not pass credential to Test-WSMan — this is a connectivity probe
            # (can we reach the WinRM service?), not an authorization probe. Passing a credential
            # caused Test-WSMan to succeed with bad credentials and emit misleading log output.
            $wsmanParams = @{
                ComputerName   = $ComputerName
                Authentication = 'None'
                ErrorAction    = 'Stop'
            }

            if ($probe.useSsl) {
                $wsmanParams.UseSSL = $true
            }

            try {
                $null = Test-WSMan @wsmanParams
                $state = [ordered]@{
                    Reachable = $true
                    Transport = $probe.transport
                    Port      = $probe.port
                    Message   = "WinRM preflight succeeded over $($probe.transport.ToUpperInvariant())"
                }
                $script:RangerWinRmProbeCache[$cacheKey] = $state
                Write-RangerLog -Level debug -Message "WinRM preflight succeeded for '$ComputerName' over $($probe.transport.ToUpperInvariant())"
                return $state
            }
            catch {
                $probeMessages.Add("WSMan $($probe.transport) failed: $($_.Exception.Message)")
                continue
            }
        }

        $state = [ordered]@{
            Reachable = $true
            Transport = $probe.transport
            Port      = $probe.port
            Message   = 'WinRM preflight tooling unavailable; assuming target is reachable.'
        }
        $script:RangerWinRmProbeCache[$cacheKey] = $state
        Write-RangerLog -Level debug -Message "WinRM preflight skipped for '$ComputerName' because Test-WSMan is unavailable"
        return $state
    }

    $state = [ordered]@{
        Reachable = $false
        Transport = $null
        Port      = $null
        Message   = "WinRM preflight failed for '$ComputerName': $($probeMessages -join ' | ')"
    }
    $script:RangerWinRmProbeCache[$cacheKey] = $state
    Write-RangerLog -Level warn -Message $state.Message
    return $state
}

function Get-RangerExecutionHostContext {
    $computerName = $env:COMPUTERNAME
    $domain = $null
    $isDomainJoined = $null

    try {
        $computerSystem = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop
        $computerName = if (-not [string]::IsNullOrWhiteSpace([string]$computerSystem.Name)) { [string]$computerSystem.Name } else { $computerName }
        $domain = if (-not [string]::IsNullOrWhiteSpace([string]$computerSystem.Domain)) { [string]$computerSystem.Domain } else { $null }
        $isDomainJoined = [bool]$computerSystem.PartOfDomain
    }
    catch { Write-RangerSwallowedError -Source 'Get-RangerExecutionHostContext' -ErrorRecord $_ }

    [ordered]@{
        ComputerName    = $computerName
        Domain          = $domain
        IsDomainJoined  = $isDomainJoined
    }
}

function Get-RangerRemoteCredentialCandidates {
    param(
        [PSCredential]$ClusterCredential,

        [PSCredential]$DomainCredential
    )

    # Issue #165: domain credential must be tried before cluster credential.
    # On domain-joined Azure Local clusters the cluster/LCM account (e.g. lcm-*) is a
    # deployment service account that has no WinRM PSRemoting rights. The domain admin
    # account is the correct credential for Invoke-Command remoting. Trying cluster first
    # caused every authorization probe to fail with "Access is denied", burning a retry
    # before eventually succeeding with the domain account — or failing entirely when
    # retries were exhausted.
    $candidates = New-Object System.Collections.Generic.List[object]
    $seenUsers = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)

    if ($DomainCredential) {
        [void]$seenUsers.Add([string]$DomainCredential.UserName)
        [void]$candidates.Add([ordered]@{
            Name       = 'domain'
            Credential = $DomainCredential
            UserName   = [string]$DomainCredential.UserName
        })
    }

    if ($ClusterCredential -and $seenUsers.Add([string]$ClusterCredential.UserName)) {
        [void]$candidates.Add([ordered]@{
            Name       = 'cluster'
            Credential = $ClusterCredential
            UserName   = [string]$ClusterCredential.UserName
        })
    }

    if (-not $DomainCredential -and -not $ClusterCredential) {
        [void]$candidates.Add([ordered]@{
            Name       = 'current-context'
            Credential = $null
            UserName   = '<current-context>'
        })
    }

    return $candidates.ToArray()
}

function Test-RangerRemoteAuthorization {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ComputerName,

        [PSCredential]$Credential,

        [int]$RetryCount = 1,
        [int]$TimeoutSeconds = 0
    )

    $result = @(
        Invoke-RangerRemoteCommand -ComputerName @($ComputerName) -Credential $Credential -RetryCount $RetryCount -TimeoutSeconds $TimeoutSeconds -ScriptBlock {
            $identity = try { [System.Security.Principal.WindowsIdentity]::GetCurrent().Name } catch { $env:USERNAME }
            [ordered]@{
                computerName = $env:COMPUTERNAME
                identity     = $identity
            }
        }
    ) | Select-Object -First 1

    if ($null -eq $result) {
        throw "Authorization probe returned no data from '$ComputerName'."
    }

    return [ordered]@{
        Target             = $ComputerName
        CredentialUserName = if ($Credential) { [string]$Credential.UserName } else { '<current-context>' }
        RemoteComputerName = [string]$result.computerName
        RemoteIdentity     = [string]$result.identity
    }
}

function Resolve-RangerRemoteExecutionCredential {
    param(
        [string[]]$Targets,

        [PSCredential]$ClusterCredential,

        [PSCredential]$DomainCredential,

        [int]$RetryCount = 1,

        [int]$TimeoutSeconds = 0
    )

    $candidateResults = New-Object System.Collections.Generic.List[object]
    $targets = @($Targets | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) })
    $candidates = @(Get-RangerRemoteCredentialCandidates -ClusterCredential $ClusterCredential -DomainCredential $DomainCredential)

    if ($targets.Count -eq 0) {
        return [ordered]@{
            SelectedSource = 'none'
            Credential     = $null
            UserName       = $null
            Detail         = 'No remoting targets are configured.'
            Results        = @()
        }
    }

    foreach ($candidate in $candidates) {
        $authorizationResults = New-Object System.Collections.Generic.List[object]
        $failures = New-Object System.Collections.Generic.List[string]

        foreach ($target in $targets) {
            try {
                # Issue #157: use RetryCount 0 for authorization probes — "Access is denied" is not
                # transient and must not be retried; the actual collection run uses $RetryCount.
                $authorization = Test-RangerRemoteAuthorization -ComputerName $target -Credential $candidate.Credential -RetryCount 0 -TimeoutSeconds $TimeoutSeconds
                [void]$authorizationResults.Add($authorization)
            }
            catch {
                [void]$failures.Add(("{0}: {1}" -f $target, $_.Exception.Message))
            }
        }

        if ($failures.Count -eq 0) {
            return [ordered]@{
                SelectedSource = [string]$candidate.Name
                Credential     = $candidate.Credential
                UserName       = [string]$candidate.UserName
                Detail         = "Selected $($candidate.Name) remoting credential '$($candidate.UserName)' after authorization preflight succeeded on $($targets.Count) target(s)."
                Results        = $authorizationResults.ToArray()
            }
        }

        [void]$candidateResults.Add([ordered]@{
            Name     = [string]$candidate.Name
            UserName = [string]$candidate.UserName
            Failures = $failures.ToArray()
        })
    }

    $hostContext = Get-RangerExecutionHostContext
    $hostGuidance = if ($hostContext.IsDomainJoined -eq $false) {
        "Execution host '$($hostContext.ComputerName)' is not domain-joined. Prefer a qualified domain account (DOMAIN\\user or user@fqdn.domain), FQDN targets, and WinRM paths validated against actual remote command execution."
    }
    elseif ($hostContext.IsDomainJoined -eq $true) {
        "Execution host '$($hostContext.ComputerName)' is domain-joined to '$($hostContext.Domain)'. The failure is more likely the selected remoting credential or target-side authorization than runner domain membership."
    }
    else {
        "Execution host domain-join state could not be determined."
    }

    $failureSummary = @($candidateResults | ForEach-Object {
        "{0} credential '{1}' failed authorization: {2}" -f $_.Name, $_.UserName, ($_.Failures -join ' | ')
    }) -join ' '

    throw "No remoting credential could authorize on all targets. $failureSummary $hostGuidance"
}

function Invoke-RangerRemoteCommand {
    param(
        [Parameter(Mandatory = $true)]
        [string[]]$ComputerName,

        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock,

        [PSCredential]$Credential,
        [object[]]$ArgumentList,
        [int]$RetryCount = 1,
        [int]$TimeoutSeconds = 0,

        # Issue #26: transport selection — 'auto' tries WinRM, falls back to Arc on failure;
        # 'winrm' forces WinRM only; 'arc' forces Arc only (skips WinRM entirely)
        [ValidateSet('auto', 'winrm', 'arc')]
        [string]$TransportMode = 'auto',

        # Arc transport context — required when TransportMode is 'arc' or 'auto' fallback
        [string]$ArcResourceGroup,
        [string]$ArcSubscriptionId,

        # Wall-clock limit for the WinRM command on each node, in seconds. When set,
        # the command runs as a job and is stopped if it overruns, so one slow or
        # unresponsive node cannot hold the whole run. 0 keeps the inline call.
        [int]$HardTimeoutSeconds = 0
    )

    # ── Arc-only path ──────────────────────────────────────────────────────────
    if ($TransportMode -eq 'arc') {
        if ([string]::IsNullOrWhiteSpace($ArcResourceGroup) -or [string]::IsNullOrWhiteSpace($ArcSubscriptionId)) {
            throw [System.InvalidOperationException]::new(
                "TransportMode 'arc' requires ArcResourceGroup and ArcSubscriptionId parameters."
            )
        }
        $arcResults = Invoke-RangerArcRunCommand -MachineName $ComputerName -ScriptBlock $ScriptBlock `
            -ArgumentList $ArgumentList -ResourceGroupName $ArcResourceGroup `
            -SubscriptionId $ArcSubscriptionId -TimeoutSeconds ($TimeoutSeconds -gt 0 ? $TimeoutSeconds : 120)
        # Parse JSON output — Arc Run Command returns stdout as a string; collectors
        # that produce structured output should write ConvertTo-Json at the end.
        return @($arcResults | ForEach-Object {
            if ($_.ExitCode -ne 0) {
                Write-RangerLog -Level warn -Message "Arc Run Command returned non-zero exit on '$($_.MachineName)': $($_.Error)"
            }
            if ($_.Output) {
                try { $_.Output | ConvertFrom-Json -Depth 100 }
                catch { $_.Output }
            }
        })
    }

    $targetStates = @($ComputerName | ForEach-Object {
        [ordered]@{
            computerName = $_
            state        = Test-RangerWinRmTarget -ComputerName $_ -Credential $Credential
        }
    })

    $reachableStates = @($targetStates | Where-Object { $_.state.Reachable })
    if ($reachableStates.Count -eq 0) {
        # Issue #26: when transport is 'auto' and Arc context is available, fall back to Arc
        if ($TransportMode -eq 'auto' -and
            -not [string]::IsNullOrWhiteSpace($ArcResourceGroup) -and
            -not [string]::IsNullOrWhiteSpace($ArcSubscriptionId) -and
            (Test-RangerCommandAvailable -Name 'Invoke-AzConnectedMachineRunCommand')) {
            Write-RangerLog -Level info -Message "WinRM unreachable on all targets — falling back to Arc Run Command transport"
            $arcResults = Invoke-RangerArcRunCommand -MachineName $ComputerName -ScriptBlock $ScriptBlock `
                -ArgumentList $ArgumentList -ResourceGroupName $ArcResourceGroup `
                -SubscriptionId $ArcSubscriptionId -TimeoutSeconds ($TimeoutSeconds -gt 0 ? $TimeoutSeconds : 120)
            return @($arcResults | ForEach-Object {
                if ($_.ExitCode -ne 0) {
                    Write-RangerLog -Level warn -Message "Arc Run Command returned non-zero exit on '$($_.MachineName)': $($_.Error)"
                }
                if ($_.Output) {
                    try { $_.Output | ConvertFrom-Json -Depth 100 }
                    catch { $_.Output }
                }
            })
        }
        $messages = @($targetStates | ForEach-Object { "$($_.computerName): $($_.state.Message)" })
        throw [System.InvalidOperationException]::new("No reachable WinRM targets available. $($messages -join ' ; ')")
    }

    $unreachableTargets = @($targetStates | Where-Object { -not $_.state.Reachable } | ForEach-Object { $_.computerName })
    if ($unreachableTargets.Count -gt 0) {
        Write-RangerLog -Level warn -Message "Skipping unreachable WinRM targets: $($unreachableTargets -join ', ')"
    }

    $targetGroups = @($reachableStates | Group-Object -Property { $_.state.Transport })

    # The retry block below is a closure that cannot see module functions by name;
    # a resolved command keeps its module binding, so capture the ones it needs here.
    $rangerStartBackgroundWork = Get-RangerCommandReference -Name 'Start-RangerBackgroundWork'
    $rangerStartRemoteJob = Get-RangerCommandReference -Name 'Start-RangerRemoteJob'

    $retryBlock = {
        $results = New-Object System.Collections.Generic.List[object]
        $rangerLogPath = $script:RangerLogPath
        $rangerCurrentLogLevel = if ($script:RangerLogLevel) { [string]$script:RangerLogLevel } else { 'info' }
        $rangerShouldLogWarn = $rangerCurrentLogLevel -in @('debug', 'info', 'warn')

        # Issue #BUG4 — per-node execution: invoke each target individually so a
        # single-node WinRM failure (e.g. 0x80090304 Kerberos error on one node)
        # does not abort collection from the remaining healthy nodes. After
        # iterating all targets, re-throw the last captured exception only when
        # every node failed — this lets Invoke-RangerRetry apply its transient-
        # retry policy without masking partial-success results.
        $lastNodeError = $null
        $succeededNodes = 0

        foreach ($group in $targetGroups) {
            $groupTargets = @($group.Group | ForEach-Object { $_.computerName })

            $baseParams = @{
                ScriptBlock    = $ScriptBlock
                Authentication = 'Negotiate'
            }
            if ($Credential)   { $baseParams.Credential   = $Credential }
            if ($ArgumentList) { $baseParams.ArgumentList = $ArgumentList }
            if ($group.Name -eq 'https') { $baseParams.UseSSL = $true }

            # Issue #113: apply per-session operation timeout when configured
            if ($TimeoutSeconds -gt 0) {
                $sessionOption = New-PSSessionOption -OperationTimeout ($TimeoutSeconds * 1000) -OpenTimeout ($TimeoutSeconds * 1000)
                $baseParams.SessionOption = $sessionOption
            }

            foreach ($nodeTarget in $groupTargets) {
                $invokeParams = $baseParams.Clone()
                $invokeParams.ComputerName = @($nodeTarget)

                $rangerRemoteWarnings = @()
                # Issue #159: catch at the innermost frame so the exception is re-thrown once
                # rather than propagating through multiple layers and duplicating transcript entries.
                try {
                    if ($HardTimeoutSeconds -gt 0) {
                        $rangerRemoteJob = & $rangerStartRemoteJob -InvokeParams $invokeParams
                        $rangerRemoteJobHandedOff = $false
                        try {
                            if (-not (Wait-Job -Job $rangerRemoteJob -Timeout $HardTimeoutSeconds)) {
                                # Stopping a remote job can itself block on an unresponsive node,
                                # so the stop runs in its own runspace and is not waited for.
                                # If even that cannot start, the job is abandoned rather than stopped
                                # here: a foreground Stop-Job/Remove-Job could block past the limit.
                                $rangerRemoteJobHandedOff = $true
                                try {
                                    & $rangerStartBackgroundWork -ScriptText 'param($Job) try { $Job.StopJob() } finally { $Job.Dispose() }' -ArgumentList @(, $rangerRemoteJob) -Label "Stop remote job on '$nodeTarget'"
                                }
                                catch {
                                    Write-Debug "Background stop of the remote job on '$nodeTarget' could not start; the job is abandoned: $($_.Exception.Message)"
                                }
                                # OperationCanceledException is deliberately not in the transient
                                # list, so a command that overran is not retried for another full term.
                                throw [System.OperationCanceledException]::new("Remote command on '$nodeTarget' did not finish within $HardTimeoutSeconds seconds and was stopped.")
                            }
                            $rangerRemoteResult = Receive-Job -Job $rangerRemoteJob -WarningAction SilentlyContinue -WarningVariable +rangerRemoteWarnings -ErrorAction Stop
                        }
                        finally {
                            if (-not $rangerRemoteJobHandedOff) {
                                Remove-Job -Job $rangerRemoteJob -Force -ErrorAction SilentlyContinue
                            }
                        }
                    }
                    else {
                        $rangerRemoteResult = Invoke-Command @invokeParams -WarningAction SilentlyContinue -WarningVariable +rangerRemoteWarnings -ErrorAction Stop
                    }
                    $succeededNodes++
                    foreach ($item in @($rangerRemoteResult)) {
                        [void]$results.Add($item)
                    }
                } catch {
                    $lastNodeError = $_
                    if ($rangerShouldLogWarn -and $rangerLogPath) {
                        try {
                            Add-Content -LiteralPath $rangerLogPath -Value "[$((Get-Date).ToString('s'))][WARN] [WinRM] '$nodeTarget' failed: $($_.Exception.Message)" -Encoding UTF8 -ErrorAction SilentlyContinue
                        } catch { Write-Debug "Ranger log or cleanup step failed (ignored): $($_.Exception.Message)" }
                    }
                }

                foreach ($w in @($rangerRemoteWarnings)) {
                    $warningMessage = if ($w -is [System.Management.Automation.WarningRecord]) { [string]$w.Message } else { [string]$w }
                    if ($rangerShouldLogWarn -and -not [string]::IsNullOrWhiteSpace($warningMessage) -and $rangerLogPath) {
                        try {
                            Add-Content -LiteralPath $rangerLogPath -Value "[$((Get-Date).ToString('s'))][WARN] [$nodeTarget] $warningMessage" -Encoding UTF8 -ErrorAction Stop
                        } catch { Write-Debug "Ranger log or cleanup step failed (ignored): $($_.Exception.Message)" }
                    }
                }
            }
        }

        # Only surface an error when every node failed — this allows Invoke-RangerRetry
        # to apply its transient-retry policy for genuine connectivity outages.
        if ($succeededNodes -eq 0 -and $null -ne $lastNodeError) {
            throw $lastNodeError.Exception
        }

        return $results.ToArray()
    }.GetNewClosure()

    $transientExceptions = @(
        'System.Net.WebException',
        'System.TimeoutException',
        'System.Net.Http.HttpRequestException',
        'Microsoft.Management.Infrastructure.CimException',
        'System.Management.Automation.Remoting.PSRemotingTransportException'
    )

    Invoke-RangerRetry -RetryCount $RetryCount -DelaySeconds 1 -Exponential -ScriptBlock $retryBlock -Label 'Invoke-RangerRemoteCommand' -Target ($ComputerName -join ',') -RetryOnExceptionType $transientExceptions
}

# Issue #26 — Arc Run Command transport
# Executes a scriptblock on one or more Arc-registered machines using
# Invoke-AzConnectedMachineRunCommand, which routes through the Azure control
# plane rather than WinRM. Used when cluster nodes are unreachable on
# ports 5985/5986 but Arc connectivity is confirmed.
#
# Limitations:
# • Requires Az.ConnectedMachine module ≥ 1.0.0
# • Output is capped at ~32 KB per execution; collectors that return large
# datasets should stream via multiple calls or use chunked output
# • The scriptblock is serialised to a string and passed as -Script; closures
# and $using: variables are not supported — pass data via ArgumentList
# • Run Commands are asynchronous on the service side; this function polls
# until the job reaches a terminal state or TimeoutSeconds is exceeded

function Invoke-RangerArcRunCommand {
    <#
    .SYNOPSIS
        Executes a scriptblock on Arc-registered machines via Azure Run Command.
    .OUTPUTS
        Array of PSCustomObject with properties: MachineName, Output, ExitCode, Error
    #>

    param(
        [Parameter(Mandatory = $true)]
        [string[]]$MachineName,

        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock,

        [object[]]$ArgumentList,

        [Parameter(Mandatory = $true)]
        [string]$ResourceGroupName,

        [Parameter(Mandatory = $true)]
        [string]$SubscriptionId,

        [string]$Location,

        [int]$TimeoutSeconds = 120,
        [int]$PollIntervalSeconds = 5
    )

    if (-not (Test-RangerCommandAvailable -Name 'Invoke-AzConnectedMachineRunCommand')) {
        throw [System.InvalidOperationException]::new(
            "Az.ConnectedMachine module is not available. Install it with: Install-Module Az.ConnectedMachine -Force"
        )
    }

    $scriptText = $ScriptBlock.ToString()

    # Inject ArgumentList values as variable assignments at the top of the script.
    # Arc Run Command does not support -ArgumentList natively; we serialise each
    # argument as JSON and assign it to $args[0], $args[1] … inside the script.
    if ($ArgumentList -and $ArgumentList.Count -gt 0) {
        $argAssignments = for ($i = 0; $i -lt $ArgumentList.Count; $i++) {
            $serialised = $ArgumentList[$i] | ConvertTo-Json -Depth 10 -Compress
            "`$args_$i = '$($serialised -replace "'", "''")' | ConvertFrom-Json"
        }
        $scriptText = ($argAssignments -join "`n") + "`n" + $scriptText
    }

    $results = New-Object System.Collections.Generic.List[object]

    foreach ($machine in $MachineName) {
        Write-RangerLog -Level debug -Message "Arc Run Command: submitting to machine '$machine' in RG '$ResourceGroupName'"

        $runParams = @{
            MachineName       = $machine
            ResourceGroupName = $ResourceGroupName
            SubscriptionId    = $SubscriptionId
            RunCommandName    = "AzureLocalRanger-$(New-Guid)"
            Script            = $scriptText
            ErrorAction       = 'Stop'
        }
        if ($Location) { $runParams.Location = $Location }

        try {
            $job = Invoke-AzConnectedMachineRunCommand @runParams -AsJob
            $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
            while ((Get-Date) -lt $deadline) {
                $state = $job | Get-Job -ErrorAction SilentlyContinue
                if (-not $state -or $state.State -in @('Completed', 'Failed', 'Stopped')) { break }
                Start-Sleep -Seconds $PollIntervalSeconds
            }

            if ($job.State -eq 'Running') {
                $job | Stop-Job -ErrorAction SilentlyContinue
                $job | Remove-Job -Force -ErrorAction SilentlyContinue
                [void]$results.Add([PSCustomObject]@{
                    MachineName = $machine
                    Output      = $null
                    ExitCode    = -1
                    Error       = "Arc Run Command timed out after $TimeoutSeconds seconds"
                })
                Write-RangerLog -Level warn -Message "Arc Run Command timed out for machine '$machine'"
                continue
            }

            $jobResult = $job | Receive-Job -ErrorAction SilentlyContinue
            $job | Remove-Job -Force -ErrorAction SilentlyContinue

            $output = if ($jobResult -and $jobResult.Value) {
                # InstanceViewOutput has a .Message property that contains stdout
                @($jobResult.Value | ForEach-Object { $_.Message }) -join "`n"
            } else {
                $null
            }

            [void]$results.Add([PSCustomObject]@{
                MachineName = $machine
                Output      = $output
                ExitCode    = 0
                Error       = $null
            })
            Write-RangerLog -Level debug -Message "Arc Run Command succeeded for machine '$machine'"
        }
        catch {
            [void]$results.Add([PSCustomObject]@{
                MachineName = $machine
                Output      = $null
                ExitCode    = -1
                Error       = $_.Exception.Message
            })
            Write-RangerLog -Level warn -Message "Arc Run Command failed for machine '$machine': $($_.Exception.Message)"
        }
    }

    return $results.ToArray()
}

function Test-RangerArcTransportAvailable {
    <#
    .SYNOPSIS
        Returns $true when the Arc Run Command transport can be used for the given config.
    .DESCRIPTION
        Checks:
          1. Az.ConnectedMachine cmdlet is present
          2. Az context is active
          3. subscriptionId and resourceGroup are configured and non-placeholder
    #>

    param(
        [Parameter(Mandatory = $true)]
        [System.Collections.IDictionary]$Config
    )

    if (-not (Test-RangerCommandAvailable -Name 'Invoke-AzConnectedMachineRunCommand')) {
        return $false
    }

    if (-not (Test-RangerCommandAvailable -Name 'Get-AzContext')) {
        return $false
    }

    $ctx = Get-AzContext -ErrorAction SilentlyContinue
    if (-not $ctx) {
        return $false
    }

    $subId = [string]$Config.targets.azure.subscriptionId
    $rg    = [string]$Config.targets.azure.resourceGroup
    if ([string]::IsNullOrWhiteSpace($subId) -or [string]::IsNullOrWhiteSpace($rg)) {
        return $false
    }

    if ((Test-RangerPlaceholderValue -Value $subId -FieldName 'targets.azure.subscriptionId') -or
        (Test-RangerPlaceholderValue -Value $rg   -FieldName 'targets.azure.resourceGroup')) {
        return $false
    }

    return $true
}

function Invoke-RangerRedfishRequest {
    param(
        [Parameter(Mandatory = $true)]
        [string]$Uri,

        [Parameter(Mandatory = $true)]
        [PSCredential]$Credential,

        [string]$Method = 'Get'
    )

    # Issue #162: pass -Label and -Target so retry detail entries in audit-manifest.json
    # carry a meaningful label ('Invoke-RangerRedfishRequest') and the actual URI instead of
    # the generic 'operation' label and an empty target string.
    # Issue #172: 4xx responses are permanent — skip retry immediately so we don't waste
    # ~45 seconds per node retrying endpoints that simply do not exist on this iDRAC version.
    Invoke-RangerRetry -RetryCount 1 -Label 'Invoke-RangerRedfishRequest' -Target $Uri -ShouldRetry {
        param($err)
        if ($err.Exception -is [Microsoft.PowerShell.Commands.HttpResponseException]) {
            $code = [int]$err.Exception.Response.StatusCode
            return $code -lt 400 -or $code -ge 500
        }
        return $true
    } -ScriptBlock {
        # Issue #329: iDRAC Redfish requires Basic auth explicitly; Invoke-RestMethod with
        # -Credential alone defaults to Negotiate (Kerberos/NTLM) which iDRAC rejects with 401.
        Invoke-RestMethod -Uri $Uri -Method $Method -Credential $Credential -Authentication Basic -SkipCertificateCheck -ContentType 'application/json' -ErrorAction Stop
    }
}

function Invoke-RangerRedfishCollection {
    param(
        [Parameter(Mandatory = $true)]
        [string]$CollectionUri,

        [Parameter(Mandatory = $true)]
        [string]$Host,

        [Parameter(Mandatory = $true)]
        [PSCredential]$Credential
    )

    $results = @()
    $collection = Invoke-RangerRedfishRequest -Uri $CollectionUri -Credential $Credential
    foreach ($member in @($collection.Members)) {
        $path = $member.'@odata.id'
        if (-not $path) {
            continue
        }

        $uri = if ($path -match '^https?://') { $path } else { "https://$Host$path" }
        try {
            $results += Invoke-RangerRedfishRequest -Uri $uri -Credential $Credential
        }
        catch {
            Write-RangerLog -Level warn -Message "Redfish member retrieval failed for '$uri': $($_.Exception.Message)"
        }
    }

    return @($results)
}

function Connect-RangerAzureContext {
    <#
    .SYNOPSIS
        v1.6.0 (#200): multi-method Azure auth chain with sovereign-cloud and
        existing-context reuse.
    .DESCRIPTION
        Dispatches to the selected method: managed-identity, service-principal
        (secret), service-principal-cert, device-code, or existing-context.
        Short-circuits to the existing context when a tenant match is found,
        avoiding MFA prompts on every run. Forwards Environment (sovereign
        cloud) and TenantId / Subscription to Connect-AzAccount.
    #>

    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '', Justification = 'Credential maps hold PSCredential objects or Key Vault references, never a plain-text secret.')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '',
        Justification = 'The Azure CLI (az account get-access-token) returns the ARM access token as a plaintext string; Connect-AzAccount -AccessToken requires a SecureString on Az.Accounts 5+, so an in-memory ConvertTo-SecureString is the only supported conversion. No secret is persisted.')]
    param(
        $AzureCredentialSettings
    )

    $settings = if ($AzureCredentialSettings) { ConvertTo-RangerHashtable -InputObject $AzureCredentialSettings } else { [ordered]@{ method = 'existing-context' } }
    $method = if ($settings.method) { [string]$settings.method } else { 'existing-context' }
    $azureEnvironment = if ($settings.environment) { [string]$settings.environment } else { $null }

    if (-not (Test-RangerCommandAvailable -Name 'Get-AzContext')) {
        return $false
    }

    # Short-circuit: if a context exists AND it matches the requested tenant
    # (when one was specified), reuse it rather than re-authenticating. This
    # avoids MFA prompts on repeated runs. #200.
    $context = Get-AzContext -ErrorAction SilentlyContinue
    $contextTenantId = if ($context -and $context.Tenant -and $context.Tenant.Id) { [string]$context.Tenant.Id } else { '' }

    # Fail fast: once an authentication attempt has failed for this exact method,
    # requested tenant/subscription and current context, every later Azure query in
    # the run returns at once instead of retrying (and re-logging) on each call.
    if ($null -eq $script:RangerAzureAuthFailures) {
        $script:RangerAzureAuthFailures = @{}
    }
    $authFailureKey = '{0}|{1}|{2}|{3}' -f $method, [string]$settings.tenantId, [string]$settings.subscriptionId, $contextTenantId
    if ($script:RangerAzureAuthFailures.ContainsKey($authFailureKey)) {
        Write-RangerLog -Level debug -Message "Connect-RangerAzureContext: skipping Azure query; authentication already failed this run ($($script:RangerAzureAuthFailures[$authFailureKey]))."
        return $false
    }

    if ($context) {
        $tenantMatches = $true
        if ($settings.tenantId -and $context.Tenant -and $context.Tenant.Id) {
            $tenantMatches = ($context.Tenant.Id -ieq [string]$settings.tenantId)
        }
        if ($tenantMatches) {
            if ($settings.subscriptionId -and $context.Subscription -and $context.Subscription.Id -ne $settings.subscriptionId -and (Test-RangerCommandAvailable -Name 'Set-AzContext')) {
                try {
                    Set-AzContext -SubscriptionId $settings.subscriptionId -ErrorAction Stop | Out-Null
                }
                catch {
                    Write-RangerLog -Level warn -Message "Failed to switch Az context to subscription '$($settings.subscriptionId)': $($_.Exception.Message)"
                }
            }
            return $true
        }

        if ($method -eq 'existing-context') {
            # existing-context has no credential of its own to switch tenants with, and
            # Ranger never starts an interactive sign-in. Say so once and stop.
            $reason = "the signed-in Az context is for tenant '$contextTenantId' but the configuration asks for tenant '$($settings.tenantId)'"
            $script:RangerAzureAuthFailures[$authFailureKey] = $reason
            Write-RangerLog -Level warn -Message "Azure queries are skipped for this run: $reason. The 'existing-context' method cannot switch tenants without signing in. Run Connect-AzAccount -Tenant '$($settings.tenantId)' (or set credentials.azure.method to azure-cli, service-principal, service-principal-cert or managed-identity) and run Ranger again."
            return $false
        }

        Write-RangerLog -Level info -Message "Existing Az context tenant '$contextTenantId' does not match requested '$($settings.tenantId)' — re-authenticating via $method."
    }
    elseif ($method -eq 'existing-context') {
        $reason = 'no Az context is signed in'
        $script:RangerAzureAuthFailures[$authFailureKey] = $reason
        Write-RangerLog -Level warn -Message "Azure queries are skipped for this run: $reason and the 'existing-context' method does not sign in. Run Connect-AzAccount (or choose another credentials.azure.method) and run Ranger again."
        return $false
    }

    try {
        switch ($method) {
            'managed-identity' {
                $connectParams = @{ Identity = $true; ErrorAction = 'Stop' }
                if ($settings.clientId)        { $connectParams.AccountId    = $settings.clientId }
                if ($settings.subscriptionId)  { $connectParams.Subscription = $settings.subscriptionId }
                if ($settings.tenantId)        { $connectParams.Tenant       = $settings.tenantId }
                if ($azureEnvironment)         { $connectParams.Environment  = $azureEnvironment }
                Connect-AzAccount @connectParams | Out-Null
                return $true
            }
            'device-code' {
                $connectParams = @{ UseDeviceAuthentication = $true; ErrorAction = 'Stop' }
                if ($settings.tenantId)        { $connectParams.Tenant       = $settings.tenantId }
                if ($settings.subscriptionId)  { $connectParams.Subscription = $settings.subscriptionId }
                if ($azureEnvironment)         { $connectParams.Environment  = $azureEnvironment }
                Connect-AzAccount @connectParams | Out-Null
                return $true
            }
            'service-principal' {
                if (-not $settings.clientSecretSecureString) {
                    throw 'Azure service-principal authentication requires a resolved client secret.'
                }

                $credential = [PSCredential]::new([string]$settings.clientId, $settings.clientSecretSecureString)
                $connectParams = @{
                    ServicePrincipal = $true
                    Tenant           = $settings.tenantId
                    Credential       = $credential
                    ErrorAction      = 'Stop'
                }
                if ($settings.subscriptionId)  { $connectParams.Subscription = $settings.subscriptionId }
                if ($azureEnvironment)         { $connectParams.Environment  = $azureEnvironment }
                Connect-AzAccount @connectParams | Out-Null
                return $true
            }
            'service-principal-cert' {
                # v1.6.0 (#200): SPN + certificate auth. Accept either a certificate
                # thumbprint from the local store or a path to a PFX/PEM file.
                if ([string]::IsNullOrWhiteSpace([string]$settings.clientId)) {
                    throw 'Azure service-principal-cert authentication requires credentials.azure.clientId.'
                }
                if ([string]::IsNullOrWhiteSpace([string]$settings.tenantId)) {
                    throw 'Azure service-principal-cert authentication requires a tenantId.'
                }
                $connectParams = @{
                    ServicePrincipal  = $true
                    ApplicationId     = [string]$settings.clientId
                    Tenant            = [string]$settings.tenantId
                    ErrorAction       = 'Stop'
                }
                if ($settings.certificateThumbprint) {
                    $connectParams.CertificateThumbprint = [string]$settings.certificateThumbprint
                }
                elseif ($settings.certificatePath) {
                    if (-not (Test-Path -Path ([string]$settings.certificatePath) -PathType Leaf)) {
                        throw "Certificate file not found: $($settings.certificatePath)"
                    }
                    $connectParams.CertificatePath = [string]$settings.certificatePath
                    if ($settings.certificatePassword) {
                        $connectParams.CertificatePassword = $settings.certificatePassword
                    }
                }
                else {
                    throw 'Azure service-principal-cert authentication requires certificateThumbprint or certificatePath.'
                }
                if ($settings.subscriptionId) { $connectParams.Subscription = $settings.subscriptionId }
                if ($azureEnvironment)        { $connectParams.Environment  = $azureEnvironment }
                Connect-AzAccount @connectParams | Out-Null
                return $true
            }
            'azure-cli' {
                if (-not (Test-RangerAzureCliAuthenticated)) {
                    throw "Azure CLI authentication was selected, but 'az account show' failed. Run 'az login' and retry."
                }

                $accountJson = (& az account show --output json 2>$null) -join [Environment]::NewLine
                if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($accountJson)) {
                    throw 'Azure CLI did not return an active account.'
                }
                $account = $accountJson | ConvertFrom-Json

                $tokenArgs = @('account', 'get-access-token', '--resource', 'https://management.azure.com/', '--output', 'json')
                if ($settings.subscriptionId) { $tokenArgs += @('--subscription', [string]$settings.subscriptionId) }
                $tokenJson = (& az @tokenArgs 2>$null) -join [Environment]::NewLine
                if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($tokenJson)) {
                    throw 'Azure CLI could not obtain an Azure Resource Manager access token for the requested subscription.'
                }
                $token = $tokenJson | ConvertFrom-Json

                $tenantId = if ($settings.tenantId) { [string]$settings.tenantId } else { [string]$account.tenantId }
                $accountId = if ($account.user -and $account.user.name) { [string]$account.user.name } else { [string]$account.name }
                $accessToken = [string]$token.accessToken
                if ([string]::IsNullOrWhiteSpace($tenantId) -or [string]::IsNullOrWhiteSpace($accountId) -or [string]::IsNullOrWhiteSpace($accessToken)) {
                    throw 'Azure CLI account/token output was missing tenantId, account identity, or accessToken.'
                }

                $accessTokenType = (Get-Command Connect-AzAccount -ErrorAction Stop).Parameters['AccessToken'].ParameterType
                $connectParams = @{
                    AccessToken = if ($accessTokenType -eq [securestring]) { ConvertTo-SecureString $accessToken -AsPlainText -Force } else { $accessToken }
                    AccountId   = $accountId
                    Tenant      = $tenantId
                    ErrorAction = 'Stop'
                }
                if ($settings.subscriptionId) { $connectParams.Subscription = [string]$settings.subscriptionId }
                if ($azureEnvironment)        { $connectParams.Environment  = $azureEnvironment }
                Connect-AzAccount @connectParams | Out-Null
                return $true
            }
            default {
                return $false
            }
        }
    }
    catch {
        # Remember the failure so the rest of the run does not try (or prompt) again
        # for every Azure query; the first caller still sees the original error.
        $script:RangerAzureAuthFailures[$authFailureKey] = "Azure sign-in via '$method' failed: $($_.Exception.Message)"
        throw
    }
}

function Reset-RangerAzureAuthState {
    <#
    .SYNOPSIS
        Clears the per-run cache of failed Azure sign-in attempts used by
        Connect-RangerAzureContext. Called at the start and end of every run.
    #>

    [CmdletBinding(SupportsShouldProcess = $false)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Resets in-memory module state only.')]
    param()

    $script:RangerAzureAuthFailures = @{}
}

function Export-RangerAzureContext {
    <#
    .SYNOPSIS
        v1.6.0 (#201): save the current Az context to a temp file for handoff
        into a background runspace.
    .DESCRIPTION
        Calls Save-AzContext to $env:TEMP\ranger-az-ctx-<guid>.json and returns
        the file path. Callers pass this path to a runspace; the runspace uses
        Import-RangerAzureContext as its first action to restore the session.
    #>

    [CmdletBinding()]
    param()

    if (-not (Test-RangerCommandAvailable -Name 'Get-AzContext')) {
        throw 'Az.Accounts module is not installed. Run Install-Module Az.Accounts -Scope CurrentUser -Force.'
    }
    $ctx = Get-AzContext -ErrorAction SilentlyContinue
    if (-not $ctx -or -not $ctx.Account) {
        throw 'No Azure context found. Run Connect-AzAccount or use Invoke-AzureLocalRanger -AzureMethod managed-identity.'
    }
    if (-not (Test-RangerCommandAvailable -Name 'Save-AzContext')) {
        throw 'Save-AzContext is not available. Az.Accounts >= 2.7 is required for background runspace context handoff.'
    }

    $root = if ($env:TEMP) { $env:TEMP } else { [System.IO.Path]::GetTempPath() }
    $path = Join-Path -Path $root -ChildPath ("ranger-az-ctx-{0}.json" -f [guid]::NewGuid().ToString('N'))
    try {
        Save-AzContext -Path $path -Force -ErrorAction Stop | Out-Null
    } catch {
        throw "Save-AzContext failed: $($_.Exception.Message)"
    }
    Write-RangerLog -Level debug -Message "Export-RangerAzureContext: Az context saved to $path"
    return $path
}

function Import-RangerAzureContext {
    <#
    .SYNOPSIS
        v1.6.0 (#201): restore an exported Az context inside a background
        runspace and delete the temp file.
    .PARAMETER Path
        Path produced by Export-RangerAzureContext.
    .PARAMETER SubscriptionId
        Optional subscription to Set-AzContext into after import.
    .PARAMETER KeepFile
        Do not delete the temp file after import. Off by default.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Path,

        [string]$SubscriptionId,

        [switch]$KeepFile
    )

    if (-not (Test-Path -Path $Path -PathType Leaf)) {
        throw "Azure context file not found: $Path"
    }
    if (-not (Get-Command -Name 'Import-AzContext' -ErrorAction SilentlyContinue)) {
        throw 'Import-AzContext is not available. Ensure Az.Accounts is installed in this runspace.'
    }

    try {
        Import-AzContext -Path $Path -ErrorAction Stop | Out-Null
    } catch {
        throw "Import-AzContext failed: $($_.Exception.Message)"
    }

    if (-not [string]::IsNullOrWhiteSpace($SubscriptionId) -and (Get-Command -Name 'Set-AzContext' -ErrorAction SilentlyContinue)) {
        try {
            Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction Stop | Out-Null
        } catch {
            Write-RangerLog -Level warn -Message "Import-RangerAzureContext: Set-AzContext to '$SubscriptionId' failed — $($_.Exception.Message)"
        }
    }

    if (-not $KeepFile) {
        try { [System.IO.File]::Delete($Path) } catch { Write-RangerSwallowedError -Source 'Import-RangerAzureContext' -ErrorRecord $_ }
    }
    return $true
}

function Invoke-RangerAzureQuery {
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '', Justification = 'Credential maps hold PSCredential objects or Key Vault references, never a plain-text secret.')]
    param(
        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock,

        [object[]]$ArgumentList,
        $AzureCredentialSettings,

        # Wall-clock limit for the query, in seconds. 0 (the default) runs the script
        # block inline as before. When set, the query runs in its own runspace in this
        # process (the Az context is process-wide, so it is shared) and is abandoned with
        # a TimeoutException if it overruns, instead of holding the collector.
        [int]$TimeoutSeconds = 0,

        # Name used in the timeout message and progress log.
        [string]$Label = 'Azure query'
    )

    if (-not (Connect-RangerAzureContext -AzureCredentialSettings $AzureCredentialSettings)) {
        return $null
    }

    if ($TimeoutSeconds -le 0) {
        return (& $ScriptBlock @ArgumentList)
    }

    return Invoke-RangerTimedScriptBlock -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -TimeoutSeconds $TimeoutSeconds -Label $Label
}

function Invoke-RangerTimedScriptBlock {
    <#
    .SYNOPSIS
        Runs a script block in a separate runspace in this process and gives up on it
        after TimeoutSeconds.
    .DESCRIPTION
        The script block is re-created from its text, so it does not see the caller's
        variables: pass everything it needs through ArgumentList. When the text calls
        Ranger helpers, the runspace imports this module first and runs the block in
        the module's scope. On timeout the runspace is told to stop without waiting
        (a blocked network call may ignore the stop for a long time) and a
        TimeoutException is thrown.
    #>

    param(
        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock,

        [object[]]$ArgumentList,

        [Parameter(Mandatory = $true)]
        [int]$TimeoutSeconds,

        [string]$Label = 'Timed action'
    )

    $scriptText = $ScriptBlock.ToString()
    $modulePath = $null
    if ($scriptText -match '\b[A-Za-z]+-Ranger[A-Za-z0-9]+\b') {
        $moduleInfo = $ExecutionContext.SessionState.Module
        if ($moduleInfo) {
            $manifest = Join-Path -Path $moduleInfo.ModuleBase -ChildPath 'AzureLocalRanger.psd1'
            $modulePath = if (Test-Path -Path $manifest -PathType Leaf) { $manifest } else { $moduleInfo.Path }
        }
    }

    $runspace = [runspacefactory]::CreateRunspace()
    $runspace.Open()
    $shell = [powershell]::Create()
    $shell.Runspace = $runspace

    if ($modulePath) {
        [void]$shell.AddScript({
            param($RangerModulePath, $RangerScriptText, $RangerArguments)
            $rangerModule = Import-Module -Name $RangerModulePath -PassThru -ErrorAction Stop -WarningAction SilentlyContinue
            & $rangerModule ([scriptblock]::Create($RangerScriptText)) @RangerArguments
        }.ToString())
        [void]$shell.AddArgument($modulePath)
        [void]$shell.AddArgument($scriptText)
        [void]$shell.AddArgument(@($ArgumentList))
    }
    else {
        [void]$shell.AddScript($scriptText)
        foreach ($argument in @($ArgumentList)) {
            [void]$shell.AddArgument($argument)
        }
    }

    $abandoned = $false
    try {
        $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
        $asyncResult = $shell.BeginInvoke()
        if (-not $asyncResult.AsyncWaitHandle.WaitOne([TimeSpan]::FromSeconds($TimeoutSeconds))) {
            # Ask it to stop without waiting, and hand it to the background list so it is
            # disposed once the stop has gone through (Clear-RangerBackgroundWork).
            try { [void]$shell.BeginStop($null, $null) } catch { Write-RangerSwallowedError -Source 'Invoke-RangerTimedScriptBlock' -ErrorRecord $_ }
            Add-RangerBackgroundWork -Shell $shell -Runspace $runspace -Label $Label
            $abandoned = $true
            throw [System.TimeoutException]::new("$Label did not finish within $TimeoutSeconds seconds and was abandoned.")
        }

        $output = $shell.EndInvoke($asyncResult)
        foreach ($record in @($shell.Streams.Error)) {
            Write-RangerLog -Level debug -Message "${Label}: $($record.Exception.Message)"
        }
        Write-RangerLog -Level debug -Message ("{0} finished in {1:N1}s in its own runspace" -f $Label, $stopwatch.Elapsed.TotalSeconds)
        foreach ($item in $output) {
            $item
        }
    }
    finally {
        if (-not $abandoned) {
            $shell.Dispose()
            $runspace.Dispose()
        }
        Clear-RangerBackgroundWork
    }
}

function Get-RangerCommandReference {
    <#
    .SYNOPSIS
        Returns a module command as an invocable object for use inside closures
        (GetNewClosure), which cannot resolve module functions by name. An alias
        (for example a Pester mock) is resolved to the command it points at.
    #>

    param(
        [Parameter(Mandatory = $true)]
        [string]$Name
    )

    $command = $ExecutionContext.InvokeCommand.GetCommand($Name, [System.Management.Automation.CommandTypes]'Alias,Function')
    if ($command -is [System.Management.Automation.AliasInfo]) {
        $command = $command.ResolvedCommand
    }
    return $command
}

function Start-RangerRemoteJob {
    <#
    .SYNOPSIS
        Starts Invoke-Command as a job for one node (hard-timeout path of
        Invoke-RangerRemoteCommand).
    #>

    param(
        [Parameter(Mandatory = $true)]
        [hashtable]$InvokeParams
    )

    return Invoke-Command @InvokeParams -AsJob -ErrorAction Stop
}

function Add-RangerBackgroundWork {
    <#
    .SYNOPSIS
        Records a PowerShell instance (and its runspace) that Ranger stopped waiting for,
        so Clear-RangerBackgroundWork can dispose it once it has finished or stopped.
    #>

    param(
        [Parameter(Mandatory = $true)]
        [powershell]$Shell,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.Runspaces.Runspace]$Runspace,

        [string]$Label
    )

    if ($null -eq $script:RangerBackgroundWork) {
        $script:RangerBackgroundWork = [System.Collections.Generic.List[object]]::new()
    }
    $script:RangerBackgroundWork.Add([pscustomobject]@{ Shell = $Shell; Runspace = $Runspace; Label = $Label })
}

function Start-RangerBackgroundWork {
    <#
    .SYNOPSIS
        Runs a short script in its own runspace without waiting for it (for cleanup that
        may block, such as stopping a remote job) and records it for later disposal.
    #>

    param(
        [Parameter(Mandatory = $true)]
        [string]$ScriptText,

        [object[]]$ArgumentList,

        [string]$Label = 'Background cleanup'
    )

    $runspace = [runspacefactory]::CreateRunspace()
    $runspace.Open()
    $shell = [powershell]::Create()
    $shell.Runspace = $runspace
    [void]$shell.AddScript($ScriptText)
    foreach ($argument in @($ArgumentList)) {
        [void]$shell.AddArgument($argument)
    }
    [void]$shell.BeginInvoke()
    Add-RangerBackgroundWork -Shell $shell -Runspace $runspace -Label $Label
}

function Clear-RangerBackgroundWork {
    <#
    .SYNOPSIS
        Disposes recorded background work that has finished, failed or stopped. Work
        that is still running is left alone and checked again on the next call.
    #>

    [CmdletBinding(SupportsShouldProcess = $false)]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Disposes in-memory runspaces only.')]
    param()

    if ($null -eq $script:RangerBackgroundWork -or $script:RangerBackgroundWork.Count -eq 0) {
        return
    }

    $finishedStates = @(
        [System.Management.Automation.PSInvocationState]::Completed,
        [System.Management.Automation.PSInvocationState]::Failed,
        [System.Management.Automation.PSInvocationState]::Stopped
    )
    foreach ($work in @($script:RangerBackgroundWork)) {
        if ($work.Shell.InvocationStateInfo.State -in $finishedStates) {
            try {
                $work.Shell.Dispose()
                $work.Runspace.Dispose()
            }
            catch {
                Write-RangerSwallowedError -Source 'Clear-RangerBackgroundWork' -ErrorRecord $_
            }
            [void]$script:RangerBackgroundWork.Remove($work)
        }
    }
}

function Test-RangerAzureCliAuthenticated {
    if (-not (Test-RangerCommandAvailable -Name 'az')) {
        return $false
    }

    & az account show --output json 2>$null | Out-Null
    return $LASTEXITCODE -eq 0
}

function Get-RangerFixtureData {
    param(
        [string]$Path
    )

    if ([string]::IsNullOrWhiteSpace($Path)) {
        return $null
    }

    $resolvedPath = Resolve-RangerPath -Path $Path
    if (-not (Test-Path -Path $resolvedPath)) {
        throw "Fixture file not found: $resolvedPath"
    }

    return Get-Content -Path $resolvedPath -Raw | ConvertFrom-Json -Depth 100
}