Skip to content

fix: capture cmdlet warnings to prevent stdout contamination breaking DSC JSON parsing#2000

Open
Gijsreyn wants to merge 2 commits into
PowerShell:masterfrom
Gijsreyn:gh-1999/main/fix-warning-stream
Open

fix: capture cmdlet warnings to prevent stdout contamination breaking DSC JSON parsing#2000
Gijsreyn wants to merge 2 commits into
PowerShell:masterfrom
Gijsreyn:gh-1999/main/fix-warning-stream

Conversation

@Gijsreyn
Copy link
Copy Markdown

PR Summary

Warnings emitted by Install-PSResource and Uninstall-PSResource were leaking to stdout, corrupting the JSON output that DSC parses after each set operation. This fix suppresses the warning stream globally in the DSC script and re-routes any per-cmdlet warnings through the trace (stderr) channel so they remain visible without breaking JSON parsing.

PR Context

DSC expects each resource operation to emit only valid JSON on stdout. PowerShell warning messages (e.g. from NuGet or module compatibility checks) were being written to stdout alongside the JSON output, causing DSC to fail when parsing the response. The fix sets $WarningPreference = 'SilentlyContinue' at the script level to prevent any unintentional warning output, while individually capturing -WarningVariable on Install-PSResource and Uninstall-PSResource and forwarding those through Write-Trace at warn level so they still appear in DSC's trace/stderr stream.

Note

It's difficult to reproduce a warning in the stream on the GitHub runners; thus, I added a simple regression test.

PR Checklist

Copilot AI review requested due to automatic review settings May 23, 2026 11:09
@Gijsreyn
Copy link
Copy Markdown
Author

@adityapatwardhan - I think perhaps for future enhancements, it can use the same mechanism that was implemented in the PSScript resource sitting in DSC's repository. I guess a function like this would do:

function Invoke-IsolatedPSResource {
    param(
        [Parameter(Mandatory)]
        [scriptblock]$ScriptBlock,
        [Parameter()]
        [hashtable]$Parameters = @{}
    )

    $traceQueue = [System.Collections.Concurrent.ConcurrentQueue[string]]::new()
    $modulePath  = Join-Path $PSScriptRoot 'Microsoft.PowerShell.PSResourceGet.psd1'

    $ps = [PowerShell]::Create()
    $null = $ps.AddScript({
        param($ModulePath)
        Import-Module $ModulePath -Force -ErrorAction Stop
        $VerbosePreference = 'Continue'
        $DebugPreference   = 'Continue'
    }).AddParameter('ModulePath', $modulePath)
    $null = $ps.AddStatement().AddScript($ScriptBlock)
    foreach ($kv in $Parameters.GetEnumerator()) {
        $null = $ps.AddParameter($kv.Key, $kv.Value)
    }

    $subscribers = @(
        Register-ObjectEvent -InputObject $ps.Streams.Warning -EventName DataAdding -MessageData $traceQueue -Action {
            $Event.MessageData.Enqueue((@{ warn = $EventArgs.ItemAdded.Message } | ConvertTo-Json -Compress))
        }
        Register-ObjectEvent -InputObject $ps.Streams.Error -EventName DataAdding -MessageData $traceQueue -Action {
            $Event.MessageData.Enqueue((@{ error = [string]$EventArgs.ItemAdded } | ConvertTo-Json -Compress))
        }
        Register-ObjectEvent -InputObject $ps.Streams.Information -EventName DataAdding -MessageData $traceQueue -Action {
            if ($null -ne $EventArgs.ItemAdded.MessageData) {
                $Event.MessageData.Enqueue((@{ info = $EventArgs.ItemAdded.MessageData.ToString() } | ConvertTo-Json -Compress))
            }
        }
        Register-ObjectEvent -InputObject $ps.Streams.Verbose -EventName DataAdding -MessageData $traceQueue -Action {
            $Event.MessageData.Enqueue((@{ debug = $EventArgs.ItemAdded.Message } | ConvertTo-Json -Compress))
        }
        Register-ObjectEvent -InputObject $ps.Streams.Debug -EventName DataAdding -MessageData $traceQueue -Action {
            $Event.MessageData.Enqueue((@{ debug = $EventArgs.ItemAdded.Message } | ConvertTo-Json -Compress))
        }
    )

    function FlushTraceQueue {
        $trace = $null
        while (!$traceQueue.IsEmpty) {
            if ($traceQueue.TryDequeue([ref]$trace)) {
                $host.ui.WriteErrorLine($trace)
            }
        }
    }

    try {
        $asyncResult = $ps.BeginInvoke()
        while (-not $asyncResult.IsCompleted) {
            FlushTraceQueue
            Start-Sleep -Milliseconds 100
        }
        $output = $ps.EndInvoke($asyncResult)
        FlushTraceQueue

        if ($ps.HadErrors) {
            throw $ps.Streams.Error[0].Exception
        }

        return $output
    }
    finally {
        $ps.Dispose()
        foreach ($subscriber in $subscribers) {
            Unregister-Event -SubscriptionId $subscriber.SubscriptionId -ErrorAction SilentlyContinue
            Remove-Job -Id $subscriber.SubscriptionId -Force -ErrorAction SilentlyContinue
        }
    }
}

If that's your preference to include instantly, let me know! :)

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR aims to prevent PSResourceGet warning output from contaminating DSC JSON output (stdout), which can break JSON parsing, and adds a regression test to validate stdout remains valid JSON.

Changes:

  • Added a Pester regression test ensuring dsc resource set ... -o json stdout contains only valid JSON (no warnings / ANSI escapes).
  • Captured warnings from Install-PSResource / Uninstall-PSResource via -WarningVariable and forwarded them to Write-Trace.
  • Set $WarningPreference = 'SilentlyContinue' to suppress warnings globally within the DSC entry script.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
test/DscResource/PSResourceGetDSCResource.Tests.ps1 Adds regression coverage to ensure stdout JSON isn’t polluted by warning output.
src/dsc/psresourceget.ps1 Attempts to suppress/capture PSResourceGet warnings and route them to trace instead of stdout.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/dsc/psresourceget.ps1
Comment thread src/dsc/psresourceget.ps1
Comment thread test/DscResource/PSResourceGetDSCResource.Tests.ps1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants