'ImportPSModule RequiredVersion is ignored

I'm trying to import a specific version of a PowerShell module. I have to do it from .NET. However, the RequiredVersion is simply ignored. Even if I use a non-existing version, it will simply use whatever version it finds on my machine.

     var moduleSpec = new Hashtable
     {
        { "ModuleName", "MicrosoftTeams" },
        { "RequiredVersion", "5.7.2" }
     };

     var iss = InitialSessionState.Create();
     iss.ImportPSModule( new List<ModuleSpecification> { new ModuleSpecification( moduleSpec ) } );
     var runspace = RunspaceFactory.CreateRunspace( iss );
     runspace.Open();

I would expect this to fail (throw an exception of some sort), but it will simply use an existing version of the module (4.2.0 on my machine).

On the other hand, running this in PS:

Import-Module MicrosoftTeams -RequiredVersion 5.7.2;

will throw this exception:

Import-Module : The specified module 'MicrosoftTeams' with version '5.7.2' was not loaded because no valid module file was found in any module directory.

What am I doing wrong in C#? This answer mentions checking the standard error list, but it's empty.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source