Vscode-powershell: WriteObject and WriteError methods cannot be called from outside the overrides

Created on 25 Jun 2020  路  10Comments  路  Source: PowerShell/vscode-powershell

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
Area-Code Formatting Issue-Bug

All 10 comments

Hmm, looking at the stack trace I thought at first it might come from here or here but just by inverting the conditions locally to force it to run those lines, the errors are not matching.

In order to investigate this we either need script files to be able to reproduce or a debug stack trace. Would you be willing to install a Debug build locally? If you download the below zip, unblock the zip and extract it to a folder like e.g. C:\Users\YourUserName\Documents\PowerShell\Modules\PSScriptAnalyzer then the vs code extension would start using it after a restart (you can check that afterwards with (Get-Command Invoke-ScriptAnalyzer).Module.Path)
PSScriptAnalyzer.zip
This is a local debug build of the current master status. If you have security concerns around how I created it, we could also modify the CI build to produce a debug artifact if you feel more comfortable downloading it from a CI build where you know the source? Let us know if so

Nah, I trust you. Don't worry. Will try it out.

[-] 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.
PS C:\Support\GitHub\PSSharedGoods> $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 from within the same thread. Validate that the cmdlet makes these calls correctly, or contact Mi
                        crosoft Customer Support Services.
                           at System.Management.Automation.MshCommandRuntime.ThrowIfWriteNotPermitted(Boolean needsToWriteToPipeline)
                           at System.Management.Automation.MshCommandRuntime.WriteHelper_ShouldWrite(ActionPreference preference, ContinueStatus lastContinueStatus)
                           at System.Management.Automation.MshCommandRuntime.WriteVerbose(VerboseRecord record, Boolean overrideInquire)
                           at System.Management.Automation.Cmdlet.WriteVerbose(String text)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeFormatterCommand.Microsoft.Windows.PowerShell.ScriptAnalyzer.IOutputWriter.WriteVerbose(String message)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.AnalyzeSyntaxTree(ScriptBlockAst scriptAst, Token[] scriptTokens, String filePath, Boolean skipVariableAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.AnalyzeScriptDefinition(String scriptDefinition, ScriptBlockAst& scriptAst, Token[]& scriptTokens, Boolean skipVariableAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.Fix(EditableText text, Range range, Boolean skipParsing, Range& updatedRange, Boolean& fixesWereApplied, ScriptBlockAst& scriptAst, Token[]& scriptTokens, Boolean skipVariableAnalysis)
                           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
PipelineIterationInfo : {}

I can reproduce it as long as I try to play in VSCode with something while I try to format long running .psm1

C:\Users\przemyslaw.klys\Documents\WindowsPowerShell\Modules\PSScriptAnalyzer\1.19.0\PSScriptAnalyzer.psm1 - I have replaced it in both places tho.

Basically once formatter is running and should be for 30+ seconds, I press CLTR+ALT+F to format any text and it errors out. I guess when I play with files some automated format kicks in and breaks it as well.

Thanks for giving it a try. Unfortunately the exception still does not contain the contain line numbers. I had a look and it seems we do not copy the PDB files (which are needed for that) in Debug builds. I opened PR PowerShell/PSScriptAnalyzer#1535 with a fix for that.
In the meantime, here is a true debug build that includes those required pdb files, sorry for that
PSScriptAnalyzer.zip

I can reproduce it - run in VSCode a script that runs Invoke-Formatter, as soon as it starts, start pressing CTRL+ALT+F multiple times (like you would trigger formatting of a file (on any file in VsCode). It will crash. It's like if formatting kicks in 2 times and they fight for resources or something.

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 from within the same thread. Validate that the cmdlet makes these calls correctly, or contact Microsoft Customer Suppo
                        rt Services.
                           at System.Management.Automation.MshCommandRuntime.ThrowIfWriteNotPermitted(Boolean needsToWriteToPipeline)
                           at System.Management.Automation.MshCommandRuntime.WriteHelper_ShouldWrite(ActionPreference preference, ContinueStatus lastContinueStatus)
                           at System.Management.Automation.MshCommandRuntime.WriteVerbose(VerboseRecord record, Boolean overrideInquire)
                           at System.Management.Automation.Cmdlet.WriteVerbose(String text)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeFormatterCommand.Microsoft.Windows.PowerShell.ScriptAnalyzer.IOutputWriter.WriteVerbose(String message)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.AnalyzeSyntaxTree(ScriptBlockAst scriptAst, Token[] scriptTokens, String filePath, Boolean skipVariableAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.AnalyzeScriptDefinition(String scriptDefinition, ScriptBlockAst& scriptAst, Token[]& scriptTokens, Boolean skipVariableAnalysis)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.Fix(EditableText text, Range range, Boolean skipParsing, Range& updatedRange, Boolean& fixesWereApplied, ScriptBlockAst& scriptAst, Token[]& scriptTokens, Boolean skipVariableAnalysis)
                           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
PipelineIterationInfo : {}

I don't think new version worked tho in terms of PDB

Thanks @PrzemyslawKlys and @bergmeister after looking at this more closely it appears that the error is likely being caused by PowerShell Editor Services rather than PSSA, since this likely cannot be replicated outside of the VSCode environment

Looking at this, I think this is related to the other PSSA errors we're seeing in the extension, and I think it's something that will be addressed by ongoing work in both PSES and PSSA

@rjmholt any ETA? like 1 week, 3 months, 6 months?

Working on several things at once at the moment, but may be able to look at a more targeted bugfix to lessen the impact here.

The other work is much larger, likely multi-month timeline. As always when people ask for ETAs in issues, all I know is what I've seen so far. I've spent about two weeks on the PSES problem and the hard part is still to come. Making PSSA work better is going to take months, since it's basically being rewritten so that it can be safely hosted.

Was this page helpful?
0 / 5 - 0 ratings