Skip to content

.NET Can't import ActiveDirectory module, works in Powershell #21232

@jprpicw

Description

@jprpicw

Prerequisites

Steps to reproduce

A console app in .NET 8, install Nuget package Microsoft.Powershell.SDK. The code used is:

using System.Management.Automation.Runspaces;
...
var initial = InitialSessionState.CreateDefault();
initial.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

initial.ImportPSModule(["ActiveDirectory"]);
using var runspace = RunspaceFactory.CreateRunspace(initial);

try
{
    runspace.Open();
}
catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}

Expected behavior

I would be able to open runspace and use it to run PS commands, since I can run the commands from the Powershell itself.

Actual behavior

Throws an exception.

Error details

Could not load file or assembly 'Microsoft.ActiveDirectory.Management, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Environment data

Name                           Value                                                                                                                                     
----                           -----                                                                                                                                     
PSVersion                      5.1.22621.2506                                                                                                                            
PSEdition                      Desktop                                                                                                                                   
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                   
BuildVersion                   10.0.22621.2506                                                                                                                           
CLRVersion                     4.0.30319.42000                                                                                                                           
WSManStackVersion              3.0                                                                                                                                       
PSRemotingProtocolVersion      2.3                                                                                                                                       
SerializationVersion           1.1.0.1

Visuals

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs-TriageThe issue is new and needs to be triaged by a work group.Resolution-AnsweredThe question is answered.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions