I am attempting to use the Microsoft.PowerShell.SDK
package to execute a PowerShell script that uses the Connect-MgGraph
command. This command works in a normal PS window, however running the script via my application leads to the "The term 'Connect-MgGraph' is not recognized as a name of a cmdlet..."
error. The PS version on my machine is 7.3.5, and the version used by my application is 7.2.10 (supported by .NET 6). It seems I am only having issues with the Graph service as I have no issues importing other modules I installed, eg. ImportExcel
. Running Get-Module -ListAvailable
through the application results in the Graph modules showing as available as expected.
public async Task<PSDataCollection<PSObject>?> Invoke(string script, CancellationToken cancellationToken)
{
try
{
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
using PowerShell shell = PowerShell.Create(iss);
shell.AddScript(script);
var outputCollection = new PSDataCollection<PSObject>();
// Uses Task.Factory to incorporate async/await
// Moves away from the old IAsyncResult functionality still used by the PowerShell API
var shellTask = Task.Factory.FromAsync(
shell.BeginInvoke<PSObject, PSObject>(null, outputCollection),
shell.EndInvoke);
PSDataCollection<PSObject> result = await shellTask.WaitAsync(cancellationToken)
.ConfigureAwait(false);
return result;
}
catch (Exception e)
{
return null;
}
}
What I've tried so far:
- Modifying
$env:PSModulePath
to ensure modules are being pulled from the proper locations.- The only difference between the module paths included in a normal PS session vs my application is that the application doesn't include
c:\program files\powershell\7\Modules
, though appending this to the path made no difference.
- The only difference between the module paths included in a normal PS session vs my application is that the application doesn't include
- Using
InitialSessionState.CreateDefault()
instead ofInitialSessionState.CreateDefault2()
to avoid loading only the commands required to host PowerShell as per Microsoft docs - Compiling my program as
x64
instead ofAny CPU
as suggested here - Consulting other similar SO questions such as this and this, though it seems they had straightforward solutions
- Importing the required modules by explicitly adding
Import-Module Microsoft.Graph -Verbose
to the script, however this producedCould not load type 'Microsoft.Graph.IAuthenticationProvider' from assembly 'Microsoft.Graph.Core, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.