Skip to content

Add-Type fails sporadically with "An item with the same key has already been added" #19470

@kborowinski

Description

@kborowinski

Prerequisites

Steps to reproduce

This is elusive but Add-Type fails sporadically with "An item with the same key has been already added" when auto-importing module on daily build of PS 7.3 (Preview.3 and Preview.4) and PS 7.2.4 as well.

It happens usually on freshly started PowerShell console session.

What is strange is that importing the failing module again but implicitly with -Force switch succeeds (please see the actual behavior)

This is not unique to specific module. In the attached example the Add-Type fails in official release of PowerShellGet module (2.2.5) - lines 517 and 796 as well as in my module KBSystemTools line 136:

PowerShellGet (file - PSModule.psm1):
~line 517

    try {
        $AddType_prams = @{
            TypeDefinition = $InternalWebProxySource
            Language       = 'CSharp'
            ErrorAction    = 'SilentlyContinue'
        }
        if (-not $script:IsCoreCLR -or $script:IsNanoServer) {
            $AddType_prams['ReferencedAssemblies'] = $RequiredAssembliesForInternalWebProxy
        }
>>>EXCEPTION>>>        Add-Type @AddType_prams
    }
    catch {
        Write-Warning -Message "InternalWebProxy: $_"
    }

~line 796

    try {
        $AddType_prams = @{
            TypeDefinition = $Win32HelpersSource
            Language       = 'CSharp'
            ErrorAction    = 'SilentlyContinue'
        }
        if ((-not $script:IsCoreCLR -or $script:IsNanoServer) -and $RequiredAssembliesForWin32Helpers) {
            $AddType_prams['ReferencedAssemblies'] = $RequiredAssembliesForWin32Helpers
        }
>>>EXCEPTION>>>        Add-Type @AddType_prams
    }
    catch {
        Write-Warning -Message "Win32Helpers: $_"
    }
}

KBSystemTools (file - KBSystemTools.psm1):
~ line 136

	$Local_ReferencedAssemblies = if ($PSVersionTable.PSVersion.Major -lt 6) {
		Add-Type -Path ([IO.Path]::Combine($PSScriptRoot, 'Assemblies', 'net20', 'Cassia.dll')) -ErrorAction Stop
		Add-Type -Path ([IO.Path]::Combine($PSScriptRoot, 'Assemblies', 'net472', 'NuGet.Versioning.dll')) -ErrorAction Stop
		Add-Type -Path ([IO.Path]::Combine($PSScriptRoot, 'Assemblies', 'net45', 'Figgle.dll')) -ErrorAction Stop
	} else {
		Add-Type -Path ([IO.Path]::Combine($PSScriptRoot, 'Assemblies', 'netstandard20', 'Cassia.dll')) -ErrorAction Stop
		Add-Type -Path ([IO.Path]::Combine($PSScriptRoot, 'Assemblies', 'netstandard20', 'NuGet.Versioning.dll')) -ErrorAction Stop
		Add-Type -Path ([IO.Path]::Combine($PSScriptRoot, 'Assemblies', 'netstandard13', 'Figgle.dll')) -ErrorAction Stop
		[String[]][IO.Directory]::EnumerateFiles([IO.Path]::Combine($PSHOME, 'ref'), '*.dll', [IO.SearchOption]::TopDirectoryOnly)
	}
>>>EXCEPTION>>>	Add-Type -TypeDefinition $Local_KBSystemToolsType -ReferencedAssemblies $Local_ReferencedAssemblies -ErrorAction Stop

Expected behavior

Add-Type should not fail.

Actual behavior

[7.2][Bukem@ATLANTIS] > Update-KBModule -Verbose
WARNING: InternalWebProxy: An item with the same key has already been added. Key: 1151434954
WARNING: Win32Helpers: An item with the same key has already been added. Key: -620943648
Update-KBModule: The term 'Update-KBModule' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
[7.2][Bukem@ATLANTIS] > Import-Module KBSystemTools -Force -Verbose
VERBOSE: Loading module from path 'D:\USERS\BUKEM\Documents\PowerShell\Modules\KBSystemTools\KBSystemTools.psd1'.
VERBOSE: Removing the imported "Compare-KBCmdletParameter" function.
VERBOSE: Removing the imported "Connect-KBShadowSession" function.
VERBOSE: Removing the imported "Find-KBModulePopular" function.
VERBOSE: Removing the imported "Find-KBModuleUpdate" function.
VERBOSE: Removing the imported "Get-KBMcAfeeEpoPattern" function.
VERBOSE: Removing the imported "Get-KBPublicIP" function.
VERBOSE: Removing the imported "Get-KBSymantecMailSecurityPattern" function.
VERBOSE: Removing the imported "Get-KBWindowsUpdate" function.
VERBOSE: Removing the imported "Install-KBWindowsUpdate" function.
VERBOSE: Removing the imported "Send-KBMouseLeftClick" function.
VERBOSE: Removing the imported "Set-KBPSEConfiguration" function.
VERBOSE: Removing the imported "Test-KBWebAccess" function.
VERBOSE: Removing the imported "Uninstall-KBOutdatedModule" function.
VERBOSE: Removing the imported "Update-KBHelp" function.
VERBOSE: Removing the imported "Update-KBModule" function.
VERBOSE: Removing the imported "Write-KBAsciiBanner" function.
VERBOSE: Loading 'FormatsToProcess' from path 'D:\USERS\BUKEM\Documents\PowerShell\Modules\KBSystemTools\Data\FormatData\KBModulePopular.Format.ps1xml'.
VERBOSE: Loading 'FormatsToProcess' from path 'D:\USERS\BUKEM\Documents\PowerShell\Modules\KBSystemTools\Data\FormatData\KBModuleUpdate.Format.ps1xml'.
VERBOSE: Loading module from path 'D:\USERS\BUKEM\Documents\PowerShell\Modules\KBSystemTools\KBSystemTools.psm1'.
VERBOSE: Importing function 'Compare-KBCmdletParameter'.
VERBOSE: Importing function 'Connect-KBShadowSession'.
VERBOSE: Importing function 'Find-KBModulePopular'.
VERBOSE: Importing function 'Find-KBModuleUpdate'.
VERBOSE: Importing function 'Get-KBMcAfeeEpoPattern'.
VERBOSE: Importing function 'Get-KBPublicIP'.
VERBOSE: Importing function 'Get-KBSymantecMailSecurityPattern'.
VERBOSE: Importing function 'Get-KBWindowsUpdate'.
VERBOSE: Importing function 'Install-KBWindowsUpdate'.
VERBOSE: Importing function 'Send-KBMouseLeftClick'.
VERBOSE: Importing function 'Set-KBPSEConfiguration'.
VERBOSE: Importing function 'Test-KBWebAccess'.
VERBOSE: Importing function 'Uninstall-KBOutdatedModule'.
VERBOSE: Importing function 'Update-KBHelp'.
VERBOSE: Importing function 'Update-KBModule'.
VERBOSE: Importing function 'Write-KBAsciiBanner'.
[7.2][Bukem@ATLANTIS] > Update-KBModule -Verbose
VERBOSE: Local module: CompletionPredictor v0.1.0
VERBOSE: Local module: Microsoft.PowerShell.ConsoleGuiTools v0.6.2
VERBOSE: Local module: Microsoft.PowerShell.Crescendo v1.0.0
VERBOSE: Local module: ScriptBlockDisassembler v1.1.0
VERBOSE: Local module: WindowsCompatibility v1.0.0
VERBOSE: Cached PSGallery module: [2022-05-26 18:33:10] Microsoft.PowerShell.Crescendo v1.0.0
VERBOSE: Cached PSGallery module: [2022-05-26 18:33:11] WindowsCompatibility v1.0.0
VERBOSE: Cached PSGallery module: [2022-05-26 18:33:11] Microsoft.PowerShell.ConsoleGuiTools v0.6.2
VERBOSE: Cached PSGallery module: [2022-05-26 18:33:10] CompletionPredictor v0.1.0
VERBOSE: Cached PSGallery module: [2022-05-26 18:33:09] ScriptBlockDisassembler v1.1.0
VERBOSE: Local module is up-to-date: CompletionPredictor
VERBOSE: Local module is up-to-date: Microsoft.PowerShell.ConsoleGuiTools
VERBOSE: Local module is up-to-date: Microsoft.PowerShell.Crescendo
VERBOSE: Local module is up-to-date: ScriptBlockDisassembler
VERBOSE: Local module is up-to-date: WindowsCompatibility

Error details

PSMessageDetails      : 
Exception             : System.Management.Automation.CommandNotFoundException: The term 'Update-KBModule' is not recognized as a name of a cmdlet, function, script file, or executable program.
                        Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
                           at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
                           at System.Management.Automation.CommandDiscovery.TryModuleAutoDiscovery(String commandName, ExecutionContext context, String originalCommandName, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, Exception& lastError)
                           at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
                           at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource)
                           at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext context)
                           at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          : Update-KBModule
CategoryInfo          : ObjectNotFound: (Update-KBModule:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

PSMessageDetails      : 
Exception             : System.ArgumentException: An item with the same key has already been added. Key: -1537659534
                           at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
                           at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.CompileToAssembly(List`1 syntaxTrees, CompilationOptions compilationOptions, EmitOptions emitOptions)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.SourceCodeProcessing()
                           at Microsoft.PowerShell.Commands.AddTypeCommand.EndProcessing()
                           at System.Management.Automation.CommandProcessorBase.Complete()
TargetObject          : 
CategoryInfo          : NotSpecified: (:) [Add-Type], ArgumentException
FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.AddTypeCommand
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, D:\USERS\BUKEM\Documents\PowerShell\Modules\KBSystemTools\KBSystemTools.psm1: line 136
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

PSMessageDetails      : 
Exception             : System.ArgumentException: An item with the same key has already been added. Key: -620943648
                           at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
                           at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.CompileToAssembly(List`1 syntaxTrees, CompilationOptions compilationOptions, EmitOptions emitOptions)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.SourceCodeProcessing()
                           at Microsoft.PowerShell.Commands.AddTypeCommand.EndProcessing()
                           at System.Management.Automation.CommandProcessorBase.Complete()
TargetObject          : 
CategoryInfo          : NotSpecified: (:) [Add-Type], ArgumentException
FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.AddTypeCommand
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, C:\program files\powershell\7\Modules\PowerShellGet\PSModule.psm1: line 796
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

PSMessageDetails      : 
Exception             : System.ArgumentException: An item with the same key has already been added. Key: 1151434954
                           at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
                           at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.CompileToAssembly(List`1 syntaxTrees, CompilationOptions compilationOptions, EmitOptions emitOptions)
                           at Microsoft.PowerShell.Commands.AddTypeCommand.SourceCodeProcessing()
                           at Microsoft.PowerShell.Commands.AddTypeCommand.EndProcessing()
                           at System.Management.Automation.CommandProcessorBase.Complete()
TargetObject          : 
CategoryInfo          : NotSpecified: (:) [Add-Type], ArgumentException
FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.AddTypeCommand
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, C:\program files\powershell\7\Modules\PowerShellGet\PSModule.psm1: line 517
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

Environment data

Name                           Value
----                           -----
PSVersion                      7.2.4
PSEdition                      Core
GitCommitId                    7.2.4
OS                             Microsoft Windows 10.0.19044
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0, 5.0, 5.1.10032.0, 6.0.0, 6.1.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Name                           Value
----                           -----
PSVersion                      7.3.0-preview.3
PSEdition                      Core
GitCommitId                    7.3.0-preview.3-139-g0882737efb830d8072dc0c2830b50a74ab2166df
OS                             Microsoft Windows 10.0.19044
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0, 5.0, 5.1.10032.0, 6.0.0, 6.1.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions