Skip to content

Invoke-ScriptAnalyzer fails intermittently with NullReferenceException in CommandInfo.ResolveParameter (ProvideCommentHelp / AvoidReservedCharInCmdlet race on Export-ModuleMember) #2229

Open

Description

Summary

Invoke-ScriptAnalyzer fails intermittently on a file that calls Export-ModuleMember -Function .... The whole call fails with a RULE_ERROR. Usually the exception is a NullReferenceException in System.Management.Automation.CommandInfo.ResolveParameter. Less often it is an InvalidOperationException from PSLocalEventManager.SubscribeEvent ("You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime.").

Environment

  • PSScriptAnalyzer 1.25.0
  • PowerShell 7.6.5 (pwsh)
  • Windows 11 Enterprise (x64)
  • Each run is a fresh pwsh -NoProfile -NonInteractive process. No profile, no other modules.

Minimal repro

  1. Create a folder with one file, Probe.psm1:

    function Get-Probe { 'probe' }
    Export-ModuleMember -Function Get-Probe
  2. Run the analyzer in a fresh process, several times:

    $fixture = '<path to the folder>'
    $child = @"
    `$ErrorActionPreference = 'Stop'
    try {
        Import-Module PSScriptAnalyzer -Force
        `$r = @(Invoke-ScriptAnalyzer -Path '$fixture' -Recurse)
        "OK count=`$(`$r.Count)"
    }
    catch { "EXC: `$(`$_.Exception.GetType().FullName): `$(`$_.Exception.Message)"; exit 3 }
    "@
    1..15 | ForEach-Object { pwsh -NoProfile -NonInteractive -Command $child }

A second fixture adds a class file beside the module (ProbeBox.ps1: class ProbeBox { [NoSuchProbeType] $Value }). It fails at a similar rate. The class file is not needed to trigger the fault.

Expected

Every run completes and returns the same findings (here: 1 finding).

Actual

Some runs fail. The whole Invoke-ScriptAnalyzer call ends with FullyQualifiedErrorId: RULE_ERROR,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeScriptAnalyzerCommand.

Stack, variant 1 (most frequent; the rule frame is ProvideCommentHelp or
AvoidReservedCharInCmdlet):

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Management.Automation.CommandInfo.ResolveParameter(String name)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper.GetExportedFunction(Ast ast)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules.AvoidReservedCharInCmdlet.AnalyzeScript(Ast ast, String fileName)+MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.<>c__DisplayClass84_1.<AnalyzeSyntaxTree>b__2()

Stack, variant 2:

System.InvalidOperationException: You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime.
   at System.Reflection.Emit.RuntimeAssemblyBuilder.DefineDynamicModuleCore(String name)
   at System.Management.Automation.PSLocalEventManager.ProcessNewSubscriber(PSEventSubscriber subscriber, Object source, String eventName, String sourceIdentifier, PSObject data, Boolean supportEvent, Boolean forwardEvent)
   at System.Management.Automation.PSLocalEventManager.SubscribeEvent(Object source, String eventName, String sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, Boolean supportEvent, Boolean forwardEvent, Int32 maxTriggerCount)
   at System.Management.Automation.PSLocalEventManager.SubscribeEvent(Object source, String eventName, String sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, Boolean supportEvent, Boolean forwardEvent, Boolean shouldQueueAndProcessInExecutionThread, Int32 maxTriggerCount)
   at System.Management.Automation.CommandInfo.GetMergedCommandParameterMetadataSafely()
   at System.Management.Automation.CommandInfo.ResolveParameter(String name)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper.GetExportedFunction(Ast ast)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules.ProvideCommentHelp.AnalyzeScript(Ast ast, String fileName)+MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.<>c__DisplayClass84_1.<AnalyzeSyntaxTree>b__2()

Frequency

Target Runs Failed
Minimal module above (Export-ModuleMember -Function) 15 6 (4 NullReferenceException, 2 InvalidOperationException)
Minimal module plus a class file 30 8
A real multi-file module (one Export-ModuleMember call), -Recurse 25 4

The same module, signed or unsigned, fails at about the same rate.

Analysis

  • The analyzer runs the rules for one file in parallel, one task per rule.
  • ProvideCommentHelp (PSProvideCommentHelp) and AvoidReservedCharInCmdlet (PSReservedCmdletChar) both call Helper.GetExportedFunction. In 1.25.0 no other caller exists.
  • GetExportedFunction calls CommandInfo.ResolveParameter on the cached Export-ModuleMember CmdletInfo. That object belongs to a runspace of the analyzer's own pool. The call comes from the rule's thread pool thread.
  • PowerShell sends such a cross-thread call through a one-shot engine event (GetMergedCommandParameterMetadataSafely). That path does not support two concurrent callers. So one rule gets a null result (variant 1), or the two subscriptions collide (variant 2).

A possible fix: resolve the Export-ModuleMember parameter metadata once, on the runspace thread, or serialize GetExportedFunction across rules.

Workaround

Run the two rules in their own passes, so that nothing else uses the analyzer's runspace at the same time:

$isolated = 'PSProvideCommentHelp', 'PSReservedCmdletChar'
$r  = @(Invoke-ScriptAnalyzer -Path $path -Recurse -ExcludeRule $isolated)
foreach ($rule in $isolated) {
    # Keep only that rule's findings: each pass reports the parse diagnostics again.
    $r += @(Invoke-ScriptAnalyzer -Path $path -Recurse -IncludeRule $rule |
        Where-Object RuleName -eq $rule)
}

With the workaround: 0 failures in 40 runs of the minimal module, 0 in 30 runs of the module with a class file, and 0 in 15 runs over three real modules. The findings are the same as those of a complete single pass.

Activity

  1. bergmeister commented on Oct 22, 2026

    @bergmeister
    Collaborator

    PR #2206 might fix that

  2. ChrisTX commented on Nov 1, 2026

    @ChrisTX

    The same thing happens on Linux (PowerShell 7.6.9 on .NET 10.0.14, PSScriptAnalyzer 1.25.0 built from the 1.25.0 tag), with the same stack:

    System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Management.Automation.CommandInfo.ResolveParameter(String name)
       at Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper.GetExportedFunction(Ast ast)
       at Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules.ProvideCommentHelp.AnalyzeScript(Ast ast, String fileName)+MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.<>c__DisplayClass84_1.<AnalyzeSyntaxTree>b__2()
    

    There's also a second symptom: most of the time, the pwsh process doesn't exit after this error. It hangs forever at about 0% CPU, even when the script catches the error. That's how we noticed it: a pre-commit hook running Invoke-ScriptAnalyzer on two files (a .ps1 and a .psm1 with Export-ModuleMember -Function ...) hung intermittently.

    Out of 15 runs of pwsh -NoProfile -NonInteractive -CommandWithArgs '$ErrorActionPreference = "Stop"; foreach ($path in $args) { Invoke-ScriptAnalyzer -Path $path }' a.ps1 b.psm1:

    • 7 were clean
    • 1 failed with the NullReferenceException
    • 7 printed the NullReferenceException and then hung (killed after 30 s)

    With -ExcludeRule PSProvideCommentHelp, PSReservedCmdletChar, 30 of 30 runs were clean.

    Why it hangs:

    • In the hung process, the main thread has returned from Main and is in ThreadStore::WaitForOtherThreads, so the runtime is waiting for foreground threads. The only threads left are the TP gate, timer, sockets and IPC threads plus two Pipeline Execution Threads.

    • Those are the worker threads of the runspaces in CommandInfoCache's runspace pool. A pool runspace uses PSThreadOptions.ReuseThread, and its PipelineThread is a foreground thread.

    • Normally they end when the primary runspace closes and disposes all other open runspaces. After the race, though, one pool runspace is left Busy with a Get-Command pipeline still Running (from Get-Runspace in the same process right after catching the exception):

      Id           : 3
      State        : Opened
      Availability : Busy
      Running      : Running Get-Command
      

      That pipeline never completes, so its thread keeps the process alive. CommandInfoCache is never disposed, and ScriptAnalyzer.CleanUp() doesn't dispose it either.

    This fits the analysis above: GetMergedCommandParameterMetadataSafely runs the metadata lookup on the rule's thread against the pool runspace's ExecutionContext when that runspace looks idle, and it dispatches through the engine event when the runspace is busy. Neither path is safe while other rule threads use the same runspace for Get-Command.

    #2206 replaces the ResolveParameter call in GetExportedFunction, but it's a large change. A minimal fix for this call site alone: Export-ModuleMember has no dynamic parameters, so its static metadata can be used without touching any runspace.

    -            CommandInfo exportMM = Helper.Instance.GetCommandInfo("export-modulemember", CommandTypes.Cmdlet);
    +            // Export-ModuleMember has no dynamic parameters, so its parameters are taken from the static
    +            // metadata of the cmdlet. CommandInfo.ResolveParameter() would use the runspace the cached
    +            // CommandInfo comes from, which races with the other rules running in parallel.
    +            List<ParameterMetadata> exportMMParams = ParameterMetadata.GetParameterMetadata(typeof(Microsoft.PowerShell.Commands.ExportModuleMemberCommand)).Values
    +                .Concat(ParameterMetadata.GetParameterMetadata(typeof(CommonParameters)).Values).ToList();
    
                 // switch parameters
    -            IEnumerable<ParameterMetadata> switchParams = (exportMM != null) ? exportMM.Parameters.Values.Where<ParameterMetadata>(pm => pm.SwitchParameter) : Enumerable.Empty<ParameterMetadata>();
    -
    -            if (exportMM == null)
    -            {
    -                return exportedFunctions;
    -            }
    +            IEnumerable<ParameterMetadata> switchParams = exportMMParams.Where<ParameterMetadata>(pm => pm.SwitchParameter);
    ...
    -                        var param = exportMM.ResolveParameter(paramAst.ParameterName);
    +                        var param = ResolveParameter(exportMMParams, paramAst.ParameterName);

    Here ResolveParameter is a small helper that matches the parameter's name or alias, or else a prefix of only one of them, like the parameter binder does. With this change, 100 runs in a row of the command above were clean (before, about half failed or hung). The findings of PSProvideCommentHelp are unchanged for the different forms of Export-ModuleMember (-Function, -Fun, -Function:x, positional, after -ErrorAction/-ea, -Verbose/-vb, -Alias, -Variable).

    If that would help in the meantime, I can open a small PR with just this fix, independent of #2206.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions