PowerShell / PowerShell/vscode-powershell

WriteObject and WriteError methods cannot be called from outside the overrides

Open
#2,785 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Area-Code Formatting Issue-Bug
Dominant language
TypeScript
Stars
1.9k
Forks
547
PR merge metrics
No merged PRs in 30d

Description

Since months I've been ignoring this error but I decided to ask, maybe it's something that can be addressed.

Basically my script copies all files .ps1 content, merges them into single psm1, saves it in Temp folder and executes formatter:

[-] Format-Code - Formatting on file C:\Users\przemyslaw.klys\AppData\Local\Temp\PSSharedGoods\PSSharedGoods.psm1 failed. Error: The WriteObject and WriteError methods cannot be called from outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread. Validate that the cmdlet makes these calls correctly, or contact Microsoft Customer Support Services.
FormatterSettings = @{
                    IncludeRules = @(
                        'PSPlaceOpenBrace',
                        'PSPlaceCloseBrace',
                        'PSUseConsistentWhitespace',
                        'PSUseConsistentIndentation',
                        'PSAlignAssignmentStatement',
                        'PSUseCorrectCasing'
                    )

                    Rules        = @{
                        PSPlaceOpenBrace           = @{
                            Enable             = $true
                            OnSameLine         = $true
                            NewLineAfter       = $true
                            IgnoreOneLineBlock = $true
                        }

                        PSPlaceCloseBrace          = @{
                            Enable             = $true
                            NewLineAfter       = $false
                            IgnoreOneLineBlock = $true
                            NoEmptyLineBefore  = $false
                        }

                        PSUseConsistentIndentation = @{
                            Enable              = $true
                            Kind                = 'space'
                            PipelineIndentation = 'IncreaseIndentationAfterEveryPipeline'
                            IndentationSize     = 4
                        }

                        PSUseConsistentWhitespace  = @{
                            Enable          = $true
                            CheckInnerBrace = $true
                            CheckOpenBrace  = $true
                            CheckOpenParen  = $true
                            CheckOperator   = $true
                            CheckPipe       = $true
                            CheckSeparator  = $true
                        }

                        PSAlignAssignmentStatement = @{
                            Enable         = $true
                            CheckHashtable = $true
                        }

                        PSUseCorrectCasing         = @{
                            Enable = $true
                        }
                    }
                }

If an unexpected error was thrown then please report the full error details using e.g. $error[0] | Select-Object *

PSMessageDetails      :
Exception             : System.Management.Automation.PSInvalidOperationException: The WriteObject and WriteError methods cannot be called from
                        outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called fro
                        m within the same thread. Validate that the cmdlet makes these calls correctly, or contact Microsoft Customer Support S
                        ervices.
                           at System.Management.Automation.MshCommandRuntime.ThrowIfWriteNotPermitted(Boolean needsToWriteToPipeline)
                           at System.Management.Automation.MshCommandRuntime.WriteHelper_ShouldWrite(ActionPreference preference, ContinueStatu
                        s lastContinueStatus)
                           at System.Management.Automation.MshCommandRuntime.WriteVerbose(VerboseRecord record, Boolean overrideInquire)
                           at System.Management.Automation.Cmdlet.WriteVerbose(String text)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.AnalyzeSyntaxTree(ScriptBlockAst scriptAst, Token[] sc
                        riptTokens, String filePath, Boolean skipVariableAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.AnalyzeScriptDefinition(String scriptDefinition, Scrip
                        tBlockAst& scriptAst, Token[]& scriptTokens, Boolean skipVariableAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.Fix(EditableText text, Range range, Boolean skipParsin
                        g, Range& updatedRange, Boolean& fixesWereApplied, ScriptBlockAst& scriptAst, Token[]& scriptTokens, Boolean skipVariab
                        leAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.Formatter.Format[TCmdlet](String scriptDefinition, Settings settings,
                         Range range, TCmdlet cmdlet)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeFormatterCommand.ProcessRecord()
                           at System.Management.Automation.CommandProcessor.ProcessRecord()
TargetObject          :
CategoryInfo          : InvalidOperation: (:) [Invoke-Formatter], PSInvalidOperationException
FullyQualifiedErrorId : InvalidOperation,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeFormatterCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, C:\Support\GitHub\PSPublishModule\Private\Format-Code.ps1: line 24
                        at Write-TextWithTime, C:\Support\GitHub\PSPublishModule\Private\Write-TextWithTime.ps1: line 15
                        at Format-Code, C:\Support\GitHub\PSPublishModule\Private\Format-Code.ps1: line 21
                        at Merge-Module, C:\Support\GitHub\PSPublishModule\Private\Merge-Module.ps1: line 256
                        at Start-ModuleBuilding, C:\Support\GitHub\PSPublishModule\Private\Start-ModuleBuilding.ps1: line 258
                        at New-PrepareModule, C:\Support\GitHub\PSPublishModule\Public\New-PrepareModule.ps1: line 18
                        at <ScriptBlock>, C:\Support\GitHub\PSSharedGoods\Publish\Manage-PSSharedGoods.ps1: line 153

This error shows up usually (but not always) if during the script run I do some "actions" within VSCode. Basically I run the script to "build my module" and then I continue edits in code for README or some fixes within ps1 files which shouldn't affect the formatting because I don't touch PSM1 file in the temp folder. But maybe some conflicts happen because of me using it?

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.19041.1
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

> (Get-Module -ListAvailable PSScriptAnalyzer).Version | ForEach-Object { $_.ToString() }
1.19.0
1.19.0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the failure with Windows PowerShell 5.1 and PSScriptAnalyzer 1.19.0 while invoking the formatter through the reported Format-Code and Invoke-Formatter path. Inspect the AnalyzeSyntaxTree and Formatter.Format stack frames, then confirm the fix by rerunning the module-formatting workflow without the WriteObject/WriteError thread exception.

Written by the indexing model from the issue text.

Assessment

Tech stack
powershell
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.