使用Microsoft.PowerShell.SDK调用Connect-MgGraph命令失败求助
问题:通过Microsoft.PowerShell.SDK执行Connect-MgGraph命令失败
本地PowerShell版本为7.3.5,在普通PS窗口中运行Connect-MgGraph命令完全正常,但通过依赖PowerShell 7.2.10(适配.NET 6)的应用程序,使用Microsoft.PowerShell.SDK包执行包含该命令的脚本时,出现以下错误:
The term 'Connect-MgGraph' is not recognized as a name of a cmdlet...
目前仅Graph模块存在问题,ImportExcel等其他模块导入无异常,且在应用程序内执行Get-Module -ListAvailable时,Graph模块显示为可用状态。
相关代码
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; } }
已尝试的解决方案
- 修改
$env:PSModulePath,添加c:\program files\powershell\7\Modules,无变化 - 使用
InitialSessionState.CreateDefault()替代CreateDefault2() - 将程序编译为x64而非Any CPU
- 查阅类似StackOverflow问题,未找到适用方案
- 显式添加
Import-Module Microsoft.Graph -Verbose,出现类型加载错误:Could not load type 'Microsoft.Graph.IAuthenticationProvider' from assembly 'Microsoft.Graph.Core, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
内容的提问来源于stack exchange,提问作者Anil
相关产品推荐
相关产品推荐

