3
votes

Has any one met this issue before? I plan to use C# to call AzureAD cmdlets. But I tried many ways to import the module, like:

InitialSessionState initialState = InitialSessionState.CreateDefault();
initialState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
initialState.AuthorizationManager = new System.Management.Automation.AuthorizationManager("O365");
initialState.LanguageMode = System.Management.Automation.PSLanguageMode.FullLanguage;
initialState.ImportPSModule(new string[] {"AzureAD" });
Runspace runspace = RunspaceFactory.CreateRunspace(initialState);

Or

pipeline.Commands.AddScript("Import-Module -Name AzureAD -Force; Get-Module");
var modules = pipeline.Invoke();

Or

pipeline.Commands.AddScript("Import-Module");
pipeline.Commands[0].Parameters.Add("Name", "AzureAD");
var modules = pipeline.Invoke()

No one can import the module. Even I use the full path "C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.0.131\AzureAD.psd1". I have used cmdlet "Install-Module AzureAD -Force" to install the AzureAD module in my server. There is no error when I call the import-module in C#, but when I trying to use AzureAD cmdlet like 'Connect-AzureAD' I will get the error message:

The 'Connect-AzureAD' command was found in the module 'AzureAD', but the module could not be loaded.

I have tried both the 2 System.Management.Automation.dll, the issue is the same. I tried powershell 4.0, 5.0. enter image description here

Any one has any ideas, please? Thanks very much.

By the way, the 1st version Azure AD module MSOnline works fine.

I enabled the -Verbose log in the import-module AzureAD cmdlet, then I checked the VERBOSE output in PowerShell.Streams.Verbose, I found there are just one record:

Loading module from path 'C:\Program Files (x86)\WindowsPowerShell\Modules\AzureAD\2.0.0.131\AzureAD.psd1'.

But it should have tens of verbose output as it does in powershell command prompt:

enter image description here

Thanks

-Justin

1

1 Answers

5
votes

I also can repro it on my side. I resolved it by uncheck Prefer 32-bit the platform target, more detail please refer to the screenshot.

enter image description here

As I install the AzureADPreview module, C# code I used for test:

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Import-Module AzureADPreview -Force;");
pipeline.Commands.AddScript("Connect-AzureAD");   
var result = pipeline.Invoke();

enter image description here