【发布时间】:2021-05-06 23:46:09
【问题描述】:
尝试在 .NET 5.0 项目中使用 C# 实现 Exchange Online Remote PowerShell(使用最新的 EXO PowerShell V2 模块)。我过去使用基本身份验证,并选择为非交互式脚本切换到基于证书的身份验证。背景方面,我已设置好 Azure 应用程序和证书并正常工作。
按照以下指南,我可以使用 PowerShell 提示符手动连接。
作为一个小测试,这些命令都可以正常工作(直接使用指纹或 .pfx):
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -CertificateThumbprint "" -AppId "" -Organization ""
Get-EXOMailbox -Identity ""
Disconnect-ExchangeOnline
我使用这个远程运行空间示例作为基础并尝试修改它以通过 C# 执行相同的命令:https://docs.microsoft.com/en-us/powershell/scripting/developer/hosting/creating-remote-runspaces?view=powershell-7.1
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace())
{
remoteRunspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = remoteRunspace;
powershell.AddCommand("Import-Module");
powershell.AddParameter("Name", "ExchangeOnlineManagement");
powershell.Invoke();
powershell.Commands.Clear();
powershell.AddCommand("Connect-ExchangeOnline");
powershell.AddParameter("AppId", "");
powershell.AddParameter("CertificateThumbprint", "");
powershell.AddParameter("Organization", "");
powershell.Invoke();
powershell.Commands.Clear();
powershell.AddCommand("Get-EXOMailbox");
powershell.AddParameter("Identity", "");
powershell.Invoke();
Collection<PSObject> results = powershell.Invoke();
powershell.Commands.Clear();
powershell.AddCommand("Disconnect-ExchangeOnline");
powershell.Invoke();
}
remoteRunspace.Close();
}
在项目中,据我所知,我正在使用所有最新的 NuGet 包。
Microsoft.PowerShell.SDK 7.1.1System.Management.Automation 7.1.1.NET 5.0 用于目标框架
此错误发生在第二行 powershell.Invoke() Connect-ExchangeOnline 命令。
System.Management.Automation.RuntimeException: 'Could not load type 'System.Security.Cryptography.SHA256Cng' from assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=....'.. '
为 Import-Module 包含 UseWindowsPowerShell 参数没有帮助。如果我删除与Connect-ExchangeOnline 关联的行,则会在Get-EXOMailbox 之前提到使用该命令的错误,因此该模块似乎至少可以正确导入。
无法从 Microsoft 找到更新的 C# 示例或指南。我应该使用不同的 NuGet 包,还是我还缺少其他东西?更好的方法?
不胜感激,谢谢!
编辑:包括一些有些相关的链接。
https://github.com/Azure/azure-functions-powershell-worker/issues/503#issuecomment-670676511
编辑 2:返回并确保我安装了模块的 2.0.4-Preview2 版本,因为这是唯一支持 PowerShell Core 的模块。更新到预览版后没有加密错误,但仍然在同一行出错。
Inner Exception 1:
PSRemotingDataStructureException: An error has occurred which PowerShell cannot handle. A remote session might have ended.
Inner Exception 2:
NotSupportedException: BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.
【问题讨论】:
标签: c# powershell .net-core exchange-server .net-5