0

When I run this PowerShell script in ISE on the server, it works:

# Connect to Exchange Online
$CertThumbPrint = "111"
$AppID = "222"
$Org = "333.onmicrosoft.com"
Connect-ExchangeOnline -CertificateThumbPrint $CertThumbPrint -AppID $AppID -Organization $Org

# Get Mailboxes
$Mailboxes = Get-Mailbox -ResultSize 5 
Write-Output $Mailboxes | format-table 

When I run it on the same server within a .net core 9 application in IIS using this c# code:

var mailboxes = new List<IrMailBox>();

                using var runspace = RunspaceFactory.CreateRunspace();
                runspace.Open();

                using var pipeline = runspace.CreatePipeline();

                
                
                string script = @"
        Set-ExecutionPolicy Unrestricted -Scope Process;
        Import-Module ExchangeOnlineManagement;
        Connect-ExchangeOnline -AppId '123' -CertificateThumbprint '123' -Organization '123.onmicrosoft.com';
        Get-ExoMailbox -ResultSize Unlimited
        ";
                
                //       
                //Get-ExoMailbox -ResultSize Unlimited | Select-Object DisplayName,PrimarySmtpAddress,RecipientTypeDetailsGet-ExoMailbox -ResultSize Unlimited | Select-Object DisplayName,PrimarySmtpAddress,RecipientTypeDetails

                pipeline.Commands.AddScript(script);
                var results = pipeline.Invoke();

                foreach (var result in results)
                {
                    var psObject = result.BaseObject as PSObject;
                    if (psObject != null)
                    {
                        mailboxes.Add(new IrMailBox
                        {
                            DisplayName = psObject.Properties["DisplayName"]?.Value?.ToString(),
                            PrimarySmtpAddress = psObject.Properties["PrimarySmtpAddress"]?.Value?.ToString()
                        });
                    }
                }

                runspace.Close();
                return mailboxes;

I get this error:

2025-05-24 19:05:37.344 +02:00 [ERR] HTTP GET /ExchangeOnline/Mailboxes/All responded 500 in 3445.1697 ms
System.Management.Automation.RuntimeException: Could not load file or assembly 'C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.8.0\netCore\Microsoft.Identity.Client.dll'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
 ---> System.IO.FileLoadException: Could not load file or assembly 'C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.8.0\netCore\Microsoft.Identity.Client.dll'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
File name: 'C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.8.0\netCore\Microsoft.Identity.Client.dll'
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at System.Reflection.Assembly.LoadFromResolveHandler(Object sender, ResolveEventArgs args)
   at System.Runtime.Loader.AssemblyLoadContext.InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, String name)
   --- End of inner exception stack trace ---
   at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
   at System.Management.Automation.Runspaces.Pipeline.Invoke()
   at IntensiveReports.Classes.PowerShellClientWrapper.GetGraphAllExchangeMailboxes(String _filterstring) in D:\prog\visual studio\IntensiveReports\IntensiveReports\Classes\PowerShellClientWrapper.cs:line 58
   at IntensiveReports.Pages.ExchangeOnline.Mailboxes.AllMailboxes.GetAllMailboxes() in D:\prog\visual studio\IntensiveReports\IntensiveReports\Pages\ExchangeOnline\Mailboxes\AllMailboxes.razor:line 71
   at IntensiveReports.Pages.ExchangeOnline.Mailboxes.AllMailboxes.OnInitializedAsync() in D:\prog\visual studio\IntensiveReports\IntensiveReports\Pages\ExchangeOnline\Mailboxes\AllMailboxes.razor:line 66
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext, Int32 frameIndex)
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& diffContext, Int32 frameIndex)
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, Int32 componentId, ArrayRange`1 oldTree, ArrayRange`1 newTree)
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(Int32 componentId, RenderFragment renderFragment)
   at Microsoft.AspNetCore.Components.Endpoints.SSRRenderModeBoundary.SetParametersAsync(ParameterView parameters)
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.SupplyCombinedParameters(ParameterView directAndCascadingParameters)
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(Int32 componentId, ParameterView initialParameters)
   at Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.BeginRenderingComponent(IComponent component, ParameterView initialParameters)
   at Microsoft.AspNetCore.Components.Endpoints.EndpointHtmlRenderer.<>c__DisplayClass40_0.<PrerenderComponentAsync>b__0()
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<InvokeAsync>g__Execute|9_0[TResult](ValueTuple`3 state)
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Components.Endpoints.EndpointHtmlRenderer.PrerenderComponentAsync(HttpContext httpContext, Type componentType, IComponentRenderMode prerenderMode, ParameterView parameters, Boolean waitForQuiescence)
   at Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
   at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count)
   at IntensiveReports.Pages.Pages__Host.ExecuteAsync() in D:\prog\visual studio\IntensiveReports\IntensiveReports\Pages\_Host.cshtml:line 5
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)

I have identified the error comes up when running 'Get-ExoMailbox -ResultSize Unlimited'. the commands before it work fine.

My execution-policy is unrestricted since this was an issue beforehand. There is only 1 version of the EXO management module installed and it was installed today. My c# project has nuget packages: Microsoft.PowerShell.SDK and System.Management.Automation installed file 'C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.8.0\netCore\Microsoft.Identity.Client.dll' does exist in version 4.66.1

Since I am not that familiar with PowerShell, would someone know how to solve this?

I have tried using copilot and google to solve this, set ExecutionPolicy to unrestriced for user, machine and enabled running of scripts for the machine, but I'm lost on this one.

5

1 Answer 1

0

Thank you @it all makes cents

After following one of your recommended posts, I ended up at https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/choosing-the-right-nuget-package?view=powershell-7.5&viewFallbackFrom=powershell-7.2

Not really understanding the entire article, I realized that System.Management.Automation and Microsoft.PowerShell.SDK are two different implementations for more or less the same thing. So I uninstalled Microsoft.PowerShell.SDK and followed the error messages.

Thus, I had to install:

  • Microsoft.PowerShell.Diagnostics
  • System.Diagnostics.Performancecounter
  • Microsoft.powershell.consolehost
  • Microsoft.PowerShell.Commands.Utility
  • Microsoft.PowerShell.Commands.Management
  • Microsoft.WSMan.Management

afterwards, I again received an error for System.Identity.Tokens.JWT: The located assembly's manifest definition does not match the assembly reference. (0x80131040)

After some more googling I realized that this package is installed implicitly into my application. This caused it to be installed as an older version. However, I didnt know Rider displays the most recent version on the right hand side and the current version in the list on the left hand side. Installing it explicitly solved the issue.

Thank you so much!

Sign up to request clarification or add additional context in comments.

4 Comments

Choosing the right PowerShell NuGet package for your .NET project states: Microsoft.PowerShell.SDK is a meta-package that pulls together all of the components of the PowerShell SDK into a single NuGet package. A self-contained .NET application can use Microsoft.PowerShell.SDK to run arbitrary PowerShell functionality without depending on any external PowerShell installations or libraries.
For information about a self-contained .NET application, see .NET application publishing overview
The following may be of interest: stackoverflow.com/questions/58211358/…
Microsoft.PowerShell.SDK NuGet package, was probably the one to use, but glad to hear you got it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.