Exchange Online Powershell使用c#连接

时间:2016-05-30 07:40:43

标签: c# powershell office365

我一直在尝试使用Powershell进行在线交流。这是我遵循的代码;

System.Security.SecureString securePassword = new System.Security.SecureString();
    foreach (char c in AdminPass)
    {
        securePassword.AppendChar(c);
    }

    PSCredential credential = new PSCredential(AdminUser, securePassword);
    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://outlook.office365.com/powershell-liveid/"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
    connectionInfo.MaximumConnectionRedirectionCount = 2;
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            using (PowerShell powershell = PowerShell.Create())
            {
                runspace.Open(); //Its dying here
                powershell.Runspace = runspace;
                powershell.AddCommand("New-MailContact");
                powershell.AddParameter("Name", DisplayName);
                powershell.AddParameter("ExternalEmailAddress", UPN);
                Collection<PSObject> result = powershell.Invoke();
            }
        }

如上所述,它的投掷错误来自: runspace.Open()

这是错误;

  

连接到远程服务器outlook.office365.com失败,并显示以下错误消息:参数不正确。更多   有关信息,请参阅about_Remote_Troubleshooting帮助主题。

Stake Trace:

   at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
   at System.Management.Automation.Runspaces.Internal.RunspacePoolInternal.EndOpen(IAsyncResult asyncResult)
   at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.Open()
   at System.Management.Automation.RemoteRunspace.Open()
   at AzureAD.Helper.UserManagement.CreateContact(String DisplayName, String MailNickName, String Password, String UPN, String ImmutableId, String AdminUser, String AdminPass, String tenantName) in :line 263
   at AzureAD.Program.<CreateCompleteUsercn>d__3.MoveNext() in 

有什么线索吗?

1 个答案:

答案 0 :(得分:0)

此代码也对我有用。如果AdminUser或AdminPassword不正确,则会出现“访问被拒绝”错误,因此不会成为问题。我看到这篇文章已有两年历史了,我记得在添加此端点(outlook.office365.com)之后,它并没有在所有时间都起作用。现在为您工作吗?如果没有,也许尝试旧的端点https://ps.outlook.com/powershell

或者,您可以使用Import-PSSession而不是WSMan进行连接。有关更多信息,请参见Exchange PowerShell commands through C#