ASP.NET core 5 web api 通过 powershell 脚本连接 exchange

ASP.NET core 5 web api connect exchange via powershell script

在我的 asp.net 核心 5 项目中,我想执行下面的 ps 脚本。该脚本可以在本机 powershell 中无错误地执行。我可以在我的项目上下文中 运行 简单的 ps 脚本。但是如果我 运行 这个脚本通过 IIS Express(与本机 powershell 相同的机器)那么它会抛出以下错误消息:

Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.

消息属于 Import-PSSession 命令。如何 运行 asp.net 核心项目上下文中的脚本?

$Username = 'user'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

$ExchangeFQDN = 'exchange.domain'
$ConnectionURI = "http://$($ExchangeFQDN)/powershell"
try{
    $mSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ConnectionURI -Credential $Cred -Authentication Kerberos
    Import-PSSession $mSession -DisableNameChecking
}catch{
    echo $_
}

将脚本转换为 c# 命令后,如下所示(代码片段改编自 here),我收到以下错误消息:

System.Management.Automation.Remoting.PSRemotingDataStructureException HResult=0x80131501 Message = An error has occurred which PowerShell cannot handle. A remote session might have ended. ... Inner Exception 1: NotSupportedException: BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.

我找到了解决方案 here

<EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>

只需将上面的行添加到项目文件的 <PropertyGroup> 部分。

        string username = @"domain\username";
        string password = "password";
        SecureString ssPassword = new SecureString();
        foreach (char x in password)
            ssPassword.AppendChar(x);
        PSCredential credentials = new PSCredential(username, ssPassword);
        var connInfo = new WSManConnectionInfo(new Uri(@"http://servername/powershell"), @"http://schemas.microsoft.com/powershell/Microsoft.Exchange", credentials);
        connInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
        connInfo.SkipCACheck = true;
        connInfo.SkipCNCheck = true;

        var runspace = RunspaceFactory.CreateRunspace(connInfo);
        runspace.Open();
        Pipeline plPileLine = runspace.CreatePipeline();
        Command smGetMailboxForward = new Command("get-mailbox");
        smGetMailboxForward.Parameters.Add("Identity", "john.doe");
        plPileLine.Commands.Add(smGetMailboxForward);
        Collection<PSObject> result = plPileLine.Invoke();
        plPileLine.Stop();
        runspace.Close();
        runspace.Dispose();