none
c# powershell automation in with exchange 2010 RRS feed

  • Question

  • Using the following Code:

    	    PSCredential psCredential = new PSCredential(username, password)
     
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://myexchangeserver.com/Powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", psCredential);
                connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
                connectionInfo.OpenTimeout = 1 * 60 * 1000; // 1 minute.
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos ;
     
                Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                Command getmailbox;
                Pipeline commandPipeLine;
                try
                {
                    runspace.Open();
                    getmailbox = new Command("Get-Mailbox");
                    getmailbox.Parameters.Add(new CommandParameter("Identity", mailboxIdentity));
                    commandPipeLine = runspace.CreatePipeline();
                    commandPipeLine.Commands.Add(getmailbox);
                    Collection<PSObject> getmailboxResults = commandPipeLine.Invoke();
     
                    if (getmailboxResults.Count > 0)
                    {
                        foreach (PSObject getMailboxResult in getmailboxResults)
                        {
     
                        }
                    }
                }
                catch (Exception exp)
                {
                    string expectionText = exp.Message;
                    string innerExceptionText = exp.InnerException.Message;
                    string stackTrace = exp.StackTrace;
                }
    

    I get an authentication when runspace.Open() is executed. The error text is:

    Connecting to remote server failed with the following error message : Logon failure: unknown user name or bad password. For more information, see the about_Remote_Troubleshooting Help topic.

    I have confirmed that the username and password are correct. The password is converted to a secure string prior to createding the PSCredential.
    I can run EMS commands from the shell on the workstation that I am running this code from.

    1. Any Ideas on why my authentication is failing?

    2. It seems like a security risk to have credentials required within the program. Is there a way to get the credentials of the currently running user and use those for the remote connection. The EMS uses the current credentials that's what I would like to be able to do as well.

    Origionally I was using the following method to setup a Runspace:

                RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
                PSSnapInException snapInException = null;
                PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
     
     
                Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig);

    This is the method I have used for exchange 2007 (other than changing the SnapIn to the 2010 version) and it used to work fine. If this method is used the following error occurs when the coomand pipeline is invoked:


    Value cannot be null.
    Parameter name: parameters

    I have set all the parameters for the getmailbox.


    Any assistance or suggestions would be great.

    Thanks

    Bill
    Saturday, February 4, 2012 5:45 AM

Answers

  • If you want to use the currently logged on users credentials then use something like this
                    WSManConnectionInfo wsConnectionInfo = new WSManConnectionInfo(new Uri("https://" + ServerName + "/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", (PSCredential)null);
                    wsConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential;
                    //Ignore SSL Errors
                    wsConnectionInfo.SkipCACheck = true;
                    wsConnectionInfo.SkipCNCheck = true;
                    Runspace rsRemoteRunspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(wsConnectionInfo);
                    rsRemoteRunspace.Open();
    


    Against a default install of Exchange generally you set the AuthenticationMechanism to be Basic and then make sure you use Https

                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://" + snServerName + "/PowerShell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
    

    3. Using the Snap-in directly should work (but only directly on a Exchange Server) there are differences in the cmdlets and the way Exchange permissions work in 2010 so that maybe an actual problem with the way your running the cmdlet but i can't see that from what you have posted.

    Cheers
    Glen

     

     

    Monday, February 6, 2012 4:32 AM

All replies

  • If you want to use the currently logged on users credentials then use something like this
                    WSManConnectionInfo wsConnectionInfo = new WSManConnectionInfo(new Uri("https://" + ServerName + "/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", (PSCredential)null);
                    wsConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential;
                    //Ignore SSL Errors
                    wsConnectionInfo.SkipCACheck = true;
                    wsConnectionInfo.SkipCNCheck = true;
                    Runspace rsRemoteRunspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(wsConnectionInfo);
                    rsRemoteRunspace.Open();
    


    Against a default install of Exchange generally you set the AuthenticationMechanism to be Basic and then make sure you use Https

                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://" + snServerName + "/PowerShell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
    

    3. Using the Snap-in directly should work (but only directly on a Exchange Server) there are differences in the cmdlets and the way Exchange permissions work in 2010 so that maybe an actual problem with the way your running the cmdlet but i can't see that from what you have posted.

    Cheers
    Glen

     

     

    Monday, February 6, 2012 4:32 AM
  • Hi Glen,

    I had figured this out over the weekend and I was just coming back to close the thread. The (PSCredential)null  is exactly what I was looking for.

    Thanks


    Bill

    Monday, February 6, 2012 8:10 PM
  • Hi, i need to create an aplication too,  create a new mailbox on exchange 2010. I found the next code, But I not have idea how implement.. can you help me please. the web aplication already create new user in Active directory, But not is funcionality for create mailbox. 

    using System;
    using System.Security;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    
    namespace PowerShellTest
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                // Prepare the credentials that will be used when connecting
                // to the server. More info on the user to use on the notes
                // below this code snippet.
                string runasUsername = @"username";
                string runasPassword = "password";
                SecureString ssRunasPassword = new SecureString();
                foreach (char x in runasPassword)
                    ssRunasPassword.AppendChar(x);
                PSCredential credentials =
                    new PSCredential(runasUsername, ssRunasPassword);
    
                // Prepare the connection
                var connInfo = new WSManConnectionInfo(
                    new Uri("http://ServersIpAddress/PowerShell"),
                    "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
                    credentials);
                connInfo.AuthenticationMechanism =
                    AuthenticationMechanism.Basic;
    
                // Create the runspace where the command will be executed
                var runspace = RunspaceFactory.CreateRunspace(connInfo);
    
                // generate the command parameters
                var testNumber = 18;
                var firstName = "Test";
                var lastName = "User" + testNumber;
                var username = "tuser" + testNumber;
                var domainName = "pedro.test.local";
                var password = "ActiveDirectoryPassword1234";
                var ssPassword = new SecureString();
                foreach (char c in password)
                    ssPassword.AppendChar(c);
    
                // create the PowerShell command
                var command = new Command("New-Mailbox");
                command.Parameters.Add("Name", firstName + " " + lastName);
                command.Parameters.Add("Alias", username);
                command.Parameters.Add(
                    "UserPrincipalName", username + "@" + domainName);
                command.Parameters.Add("SamAccountName", username);
                command.Parameters.Add("FirstName", firstName);
                command.Parameters.Add("LastName", lastName);
                command.Parameters.Add("Password", ssPassword);
                command.Parameters.Add("ResetPasswordOnNextLogon", false);
                command.Parameters.Add(
                    "OrganizationalUnit", "NeumontStudents");
    
                // Add the command to the runspace's pipeline
                runspace.Open();
                var pipeline = runspace.CreatePipeline();
                pipeline.Commands.Add(command);
    
                // Execute the command
                var results = pipeline.Invoke();
    
                runspace.Dispose();
    
                if (results.Count > 0)
                    Console.WriteLine("SUCCESS");
                else
                    Console.WriteLine("FAIL");
    
            }
        }
    }
    

    Monday, January 21, 2013 5:06 AM
  • If you have already created an Active Directory user you would need to use Enable-Mailbox http://technet.microsoft.com/en-us/library/aa998251(v=exchg.141).aspx instead of New-Mailbox (which will both create the AD Account and Mailbox).

    As far a implementation goes get your code working in a simple Console Application in Visual Studio before you try and create a Web Application from it.

    If your having problems using the code you would be better to create your own new thread in this forum with as much detail as possible on the issue your having read (read http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopmentlegacy/thread/77c07b69-eea6-43ab-9225-4b384cecfc9d for some guidelines) .

    Cheers
    Glen

    Monday, January 21, 2013 6:15 AM
  • Hi Glen and other fellows,

    I am trying to run remote powershell commands using Logged on user credentials like this:

    SManConnectionInfo wsConnectionInfo = new WSManConnectionInfo(new Uri("https://" + ServerName + "/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", (PSCredential)null);

    i.e. using

    (PSCredential)null)

    as mentioned in above answer.

    It's not working on Exchange Server 2013 CU5 with windows 2008 R2 server. Can you please give some hint why it's not working.

    Kind Regards,


    Laeeq Qazi|Team Lead(Exchange + Sharepoint + BES + DynamicsCRM) www.HostingController.com

    Monday, September 22, 2014 8:54 PM
  • The place to start would be just trying it from the console, eg can you get it to work just in the console, what authentication setting are you using in the console when it does work and try to transpose that into the code. If you specify explicit credentials does this work ? have you checked the remote powershell logs on the server to see what the server is seeing it trying to authenticate with.

    Cheers
    Glen

    Tuesday, September 23, 2014 3:48 AM
  • Hi, Thanks Glen for your reply. I have tried this with a console app, and with authentication of same user, i.e. logged on user, it works. I would check remote powershell logs, and would put my result here. Kind Regards,

    Laeeq Qazi|Team Lead(Exchange + Sharepoint + BES + DynamicsCRM) www.HostingController.com

    Thursday, September 25, 2014 10:49 AM