Skip to content

[Feature Request] Add configuration option to control PowerShell apartment state (STA / MTA) #305

@jxsword

Description

@jxsword

Description

Background

The Pester VSCode adapter currently runs PowerShell in a default apartment state (MTA) when executing tests. However, certain PowerShell modules or legacy code rely on STA (Single-Threaded Apartment) mode, which is required for proper functionality (e.g., COM interop, WPF UI controls, some third-party modules).

Through manual patching of the extension source code, I was able to force STA mode and successfully run my tests. But this requires rebuilding and installing a custom version, which is not sustainable for regular users.

Problem

There is currently no built-in way to choose the apartment state of the PowerShell runspace used by the extension. This causes test failures for users who need STA mode.

Suggested Solution

Add a user-configurable setting (e.g., pester.powerShellApartmentState) that allows switching between "STA" and "MTA" (default: "MTA" for backward compatibility). The extension should then create the PowerShell runspace with the selected apartment state.

Example configuration in settings.json:

"pester.powerShellApartmentState": "STA"

Implementation notes (for maintainers)

  • The relevant code resides in Scripts/powershellRunner.ps1 (or wherever the PowerShell runspace is created).
  • Currently, runspace creation uses [powershell]::Create() (or similar) without specifying apartment state.
  • To support STA, the runspace should be created via [runspacefactory]::CreateRunspace() and set $runspace.ApartmentState = [System.Threading.ApartmentState]::STA.
  • The configuration value could be passed from TypeScript (extension.ts) down to the PowerShell script as a parameter.

only modified code:

# Scripts\powershellRunner.ps1
# lines: 45-46
[PowerShell]$psinstance = if (!$NoSessionReuse -and (Test-Path Variable:__NODEPSINSTANCE)) {
	$GLOBAL:__NODEPSINSTANCE
}
else {
    # original code
	# [powershell]::Create()

    # modified code

	# {feiyu modify start}
	$runspace = [runspacefactory]::CreateRunspace()
	$runspace.ApartmentState = [System.Threading.ApartmentState]::STA # STA
	$runspace.Open()
	$psinstance = [powershell]::Create()
	$psinstance.Runspace = $runspace
	$psinstance
	# {feiyu modify end}
}

Why this is needed

  • Users of STA-dependent modules currently have to fork and rebuild the extension.
  • Adding this setting makes the extension more flexible and avoids obscure initialization errors.

Thank you for considering this feature!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions