How to define a dynamic module in powershell 7

Copper Contributor

.Net Core

Hello, I'm currently trying to migrate a powershell 5 script to a powershell 7 one. The goal of this script is to load the win32 api in memory using [AppDomain]::CurrentDomain and assemblies.


Here is the code :



function New-InMemoryModule {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
    Param (
        [Parameter(Position = 0)]
        $ModuleName = [Guid]::NewGuid().ToString()

    $AppDomain = [AppDomain]::CurrentDomain

    $LoadedAssemblies = $AppDomain.GetAssemblies()

    foreach ($Assembly in $LoadedAssemblies) {
        if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {
            return $Assembly

    $AssemblyName = New-Object System.Reflection.AssemblyName($ModuleName)
    $AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($AssemblyName, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
    $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName)

    return $ModuleBuilder

$Mod = New-InMemoryModule -ModuleName Win32
echo $Mod




When i execute it on powershell 5, this is the output when ran the first time :



FullyQualifiedName : Win32
MDStreamVersion    : 131072
ModuleVersionId    : 8a94565d-3e53-4cdf-9b9d-ae6da
MetadataToken      : 1
ScopeName          : Win32
Name               : <Dans le module de la        
Assembly           : Win32, Version=,      
CustomAttributes   : {}
ModuleHandle       : System.ModuleHandle




And then the second time when the module is instanced :



GAC    Version        Location
---    -------        --------
False  v4.0.30319




But when i try to execute it in powershell 7, i get the following error :



Method invocation failed because
     | [System.AppDomain] does not contain a       
     | method named 'DefineDynamicAssembly'




Do anyone has any idea if the syntax or if the way i'm suppose to call it changed ? I read the MSDN Documentation but didn't find anything.

Have a nice day !

1 Reply



This is expected since - to paraphrase the following article - Windows PowerShell leverages the full .NET Framework while PowerShell leverages .NET Core, which is a subset of the .NET Framework:



In your specific case, if you compare the class reference for System.AppDomain for the .NET Framework against the .NET Core platforms, you can clearly see (or not see, as is the case) that the .NET Core version of System.AppDomain indeed does not contain the method DefineDynamicAssembly: