简体   繁体   中英

Exchange Online Powershell connect using c#

I have been trying to connect to exchange online using Powershell. Here is a code I followed;

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

As mentioned in above like, its throwing error from like: runspace.Open()

Here is the error;

Connecting to remote server outlook.office365.com failed with the following error message : The parameter is incorrect. For more information, see the about_Remote_Troubleshooting Help topic.

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 

Any clues please?

This code worked for me as well. If the AdminUser or AdminPassword were incorrect, you would get an Access Denied error, so that can't be the issue. I see this post is a couple years old, and I remember that after this endpoint (outlook.office365.com) was added it didn't work everywhere for a time. Is this working for you now? If not, perhaps try the old endpoint https://ps.outlook.com/powershell ?

Alternatively, you could use Import-PSSession instead of WSMan to connect. See Exchange PowerShell commands through C# for more information on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM