ASP.NET CORE 5 Web API通过PowerShell脚本连接交换 [英] ASP.NET core 5 web api connect exchange via powershell script

查看:15
本文介绍了ASP.NET CORE 5 Web API通过PowerShell脚本连接交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET core 5项目中,我想执行下面的ps脚本。此脚本可以在本机PowerShell中执行而不会出现错误。我可以在我的项目上下文中运行简单的PS脚本。但如果我通过IIS Express(与本机PowerShell相同的计算机)运行此脚本,则会出现以下错误消息:

无法验证参数‘Session’上的参数。该参数为空。 为参数提供有效的值,然后尝试运行 命令。

消息属于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消息=出现错误,PowerShell 我处理不了。远程会话可能已结束。..。内部异常 1:不支持异常:BinaryForMatter序列化和 在此应用程序中禁用了反序列化。看见 https://aka.ms/binaryformatter了解更多信息。

我找到了解决方案here

<EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>

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

        string username = @"domainusername";
        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();

这篇关于ASP.NET CORE 5 Web API通过PowerShell脚本连接交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆