fix: capture cmdlet warnings to prevent stdout contamination breaking DSC JSON parsing#2000
fix: capture cmdlet warnings to prevent stdout contamination breaking DSC JSON parsing#2000Gijsreyn wants to merge 2 commits into
Conversation
… DSC JSON parsing
|
@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! :) |
There was a problem hiding this comment.
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 jsonstdout contains only valid JSON (no warnings / ANSI escapes). - Captured warnings from
Install-PSResource/Uninstall-PSResourcevia-WarningVariableand forwarded them toWrite-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.
PR Summary
Warnings emitted by
Install-PSResourceandUninstall-PSResourcewere 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-WarningVariableonInstall-PSResourceandUninstall-PSResourceand forwarding those throughWrite-Traceatwarnlevel 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
.h,.cpp,.cs,.ps1and.psm1files have the correct copyright headerWIP:or[ WIP ]to the beginning of the title (theWIPbot will keep its status check atPendingwhile the prefix is present) and remove the prefix when the PR is ready.