【问题标题】:ASP.NET core 5 web api connect exchange via powershell scriptASP.NET core 5 web api 通过 powershell 脚本连接交换
【发布时间】:2022-01-31 13:49:08
【问题描述】:

在我的 asp.net core 5 项目中,我想执行下面的 ps 脚本。此脚本可以在本机 powershell 中执行而不会出错。而且我可以在我的项目上下文中运行简单的 ps 脚本。但是,如果我通过 IIS Express(与本机 powershell 相同的机器)运行此脚本,则会引发以下错误消息:

无法验证参数“会话”的参数。参数为空。 为参数提供一个有效值,然后尝试运行 再次命令。

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

$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 $_
}

【问题讨论】:

    标签: powershell asp.net-core exchangewebservices


    【解决方案1】:

    如下所示将脚本转换为 c# 命令后(代码 sn-p 改编自 here)我 gpt 出现以下错误消息:

    System.Management.Automation.Remoting.PSRemotingDataStructureException HResult=0x80131501 消息 = PowerShell 发生错误 不能处理。远程会话可能已结束。 ... 内部异常 1:NotSupportedException:BinaryFormatter 序列化和 此应用程序中禁用了反序列化。看 https://aka.ms/binaryformatter 了解更多信息。

    我找到了解决方案here

    <EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
    

    只需将上面的行添加到您的项目文件的&lt;PropertyGroup&gt;部分。

            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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2019-07-11
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2017-02-03
      • 2020-06-09
      相关资源
      最近更新 更多