IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

New-mailbox Exchange 2010 avec C#


Sujet :

C#

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Inscrit en
    Mars 2013
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mars 2013
    Messages : 16
    Points : 8
    Points
    8
    Par défaut New-mailbox Exchange 2010 avec C#
    Bonjour,

    Voila une bonne semaine que je galère à essayer de créer des boites mails sur Exchange 2010 via mon appli C#.
    J'ai réussi à ne plus avoir de message d'erreur à l'exécution mais les boites mail ne se créent toujours pas... je désespère.
    Je vous met ci-dessous mon code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    public static PSCommand commandeMailboxUser(string firstName, string lastName, string login, string OU, string domain)
            {            
                PSCommand command = new PSCommand();
                command.AddCommand("New-Mailbox");
                command.AddParameter("Name", lastName + " " + firstName);
                command.AddParameter("Alias", login);
                command.AddParameter("OrganizationalUnit", OU);
                string UPN = login+"@"+domain;
                command.AddParameter("UserPrincipalName", UPN);
                command.AddParameter("SamAccountName", login);
                command.AddParameter("FirstName", firstName);
                command.AddParameter("Initials", "");
                command.AddParameter("LastName", lastName);            
                SecureString password = convertToSecureString("P@ssw0rd");
                command.AddParameter("Password", password);
                command.AddParameter("ResetPasswordOnNextLogon", false);            
                return command;
            }
    Cette fonction me génère ma commande PowerShell que je place en argument dans celle-ci dessous :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
     
    public static void createMailBoxUsingPS(string runasUser, SecureString runasPass, PSCommand command)
            {
                string domain = Commun.getDom();
                runasUser = runasUser + "@" +domain; 
                PSCredential credential = new PSCredential(runasUser, runasPass);
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(param.Default.httpExch), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
     
                Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
     
                PowerShell powershell = PowerShell.Create();
                powershell.Commands = command;
                try
                {
                    // open the remote runspace
                    runspace.Open();
                    // associate the runspace with powershell
                    powershell.Runspace = runspace;
                    // invoke the powershell to obtain the results                
                    powershell.Invoke();
     
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    // dispose the runspace and enable garbage collection
                    runspace.Dispose();
                    runspace = null;
                    // Finally dispose the powershell and set all variables to null to free
                    // up any resources.
                    powershell.Dispose();
                    powershell = null;
                }
            }
    La connexion au serveur fonctionne bien puisqu'un test avec un get-mailbox a été concluant mais avec ce code rien y fait...

    L'application est exécuté depuis un server 2008, j'ai testé sur un server 2003 et sur un Windows Seven mais rien y fait...

    Un détail qui est peu être important le compte qui a les droits pour créer les boite mail n'est pas le même que celui avec lequel j'exécute l'application, j'ai donc mis une fonction intermédiaire qui fait office de runas mais je ne pense pas que ça vienne de là car si je tape un autre compte qui n'a pas les droits j'ai bien une erreur comme quoi je n'ai pas les droits.

    Là je sèche complètement, je vous remercie d'avance pour votre aide.

  2. #2
    Membre expérimenté
    Avatar de charouel
    Homme Profil pro
    Freelance
    Inscrit en
    Mars 2009
    Messages
    618
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2009
    Messages : 618
    Points : 1 454
    Points
    1 454
    Billets dans le blog
    9
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    public Boolean createUserMailbox(String mail)
        {
          String err = "";
          String snapinName = "";
          String mbdb = "";
          Boolean created = false;
     
          ICollection<PSObject> results = null;
     
          // Create a runspace. We can't use the RunspaceInvoke class this time
          // because we need to get at the underlying runspace to explicitly
          // add the commands.
          RunspaceConfiguration rc = RunspaceConfiguration.Create();
          PSSnapInException snapEx = null;
     
          try
          {
            snapinName = ConfigurationManager.AppSettings["SNAPIN_NAME"].ToString();
            mbdb = ConfigurationManager.AppSettings["MBDB"].ToString();
          }
          catch (Exception e)
          {
            String function = "activeDirectory#createUserMailbox#appSettings";
            Utils.setLog(function, e.ToString(), EventLogEntryType.Error);
            return false;
          }
     
          PSSnapInInfo info = rc.AddPSSnapIn(snapinName, out snapEx);
          Runspace myRunSpace = RunspaceFactory.CreateRunspace(rc);
          myRunSpace.Open();
     
          // Create a pipeline...
          Pipeline pipeLine = myRunSpace.CreatePipeline();
     
          using (pipeLine)
          {
            // Create a command object so we can set some parameters
            // for this command.
            Command newMbx = new Command("Enable-Mailbox");
     
            newMbx.Parameters.Add("Identity", mail);
            newMbx.Parameters.Add("Alias", Utils.getSamId(mail));
            newMbx.Parameters.Add("PrimarySmtpAddress", mail);
            newMbx.Parameters.Add("Database", mbdb);
            // Add the command we've constructed
            pipeLine.Commands.Add(newMbx);
     
            // Execute the pipeline and save the objects returned.
            results = pipeLine.Invoke();
     
            // Print out any errors in the pipeline execution
            // NOTE: These error are NOT thrown as exceptions!
            // Be sure to check this to ensure that no errors
            // happened while executing the command.
            if (pipeLine.Error != null && pipeLine.Error.Count > 0)
            {
              err = "ERROR: There were pipeline errors...\n";
              foreach (object item in pipeLine.Error.ReadToEnd())
              {
                err += "Error: " + item.ToString() + "\n";
              }
     
              created = false;
            }
     
            // Print out the results of the pipeline execution
            if (results != null && results.Count > 0)
            {
              err += "MAILBOXES CREATED: Created the following mailboxes...\n";
              foreach (PSObject ps in results)
              {
                if (ps.Members["UserPrincipalName"].Value != null)
                {
                  err += "UserPrincipalName: " + ps.Members["UserPrincipalName"].Value + "\n";
                }
              }
     
              created = true;
            }
          }
     
          pipeLine = null;
          myRunSpace.Close();
          myRunSpace = null;
     
          if (!created)
          {
            String function = "activeDirectory#createUserMailbox#PowerShell";
            Utils.setLog(function, err, EventLogEntryType.Error);
          }
     
          return created;
        }
      }

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Inscrit en
    Mars 2013
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mars 2013
    Messages : 16
    Points : 8
    Points
    8
    Par défaut
    Bonjour,

    Merci pour la réponse, ça m'a permis de trouver la solution à mon problème.
    J'ai du modifier une partie du code qui ne fonctionnait pas :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    foreach (object item in pipeLine.Error.ReadToEnd())
              {
                err += "Error: " + item.ToString() + "\n";
              }
    est devenu :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    var error = pipeLineSetting.Error.Read() as Collection<ErrorRecord>;
    foreach (ErrorRecord o in error)
             {
                err += o.ToString() + "\n";
             }
    j'ai également adapté en fonction de mes besoins, ma fonction pour lancer mes commandes PS ressemble à ça maintenant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
     
    public static void InvokeExchPS(string runasUser, SecureString runasPass, Command command)
            {
                try
                {
                    string domain = Commun.getDom();
                    string err = "";
                    bool created = false;
                    runasUser = runasUser + "@" + domain;
                    ICollection<PSObject> result = null;
                    PSCredential credential = new PSCredential(runasUser, runasPass);
                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(param.Default.httpExch), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                    Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                    runspace.Open();
                    //creation pipeline pour autoriser la recherche / creation multi domaine
                    Pipeline pipeLineSetting = runspace.CreatePipeline();
                    using (pipeLineSetting)
                    {
                        Command commandSrvSetting = new Command("Set-ADServerSettings");
                        commandSrvSetting.Parameters.Add("ViewEntireForest", true);
                        pipeLineSetting.Commands.Add(commandSrvSetting);
                        result = pipeLineSetting.Invoke();
                        if (pipeLineSetting.Error != null && pipeLineSetting.Error.Count > 0)
                        {                        
                            err = "ERROR: There were pipeline errors...\n";
                            var error = pipeLineSetting.Error.Read() as Collection<ErrorRecord>;
                            foreach (ErrorRecord o in error)
                            {
                                err += o.ToString() + "\n";
                            }
                        }                                                            
                    }
                    //creation pipeline pour lancement commande PS placée en paramètre de la fonction
                    Pipeline pipeLine = runspace.CreatePipeline();
                    using (pipeLine)
                    {
                        pipeLine.Commands.Add(command);
                        result = pipeLine.Invoke();
                        if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                        {                        
                            err = "ERROR: There were pipeline errors...\n";
                            var error = pipeLine.Error.Read() as Collection<ErrorRecord>;
                            foreach (ErrorRecord o in error)
                            {
                                err += o.ToString() + "\n";
                            }                        
                            MessageBox.Show(err);                        
                            created = false;
                        }
                        if (result != null && result.Count > 0)
                        {
                            err += "MAILBOXES CREATED: Created the following mailboxes...\n";
                            foreach (PSObject ps in result)
                            {
                                if (ps.Members["UserPrincipalName"].Value != null)
                                {
                                    err += "UserPrincipalName: " + ps.Members["UserPrincipalName"].Value + "\n";
                                }                            
                            }
                            created = true;
                        }
                        pipeLine = null;
                        runspace.Close();
                        runspace = null;
                        if (!created)
                        {                        
                            MessageBox.Show(err +"\r\n--------------------------------------------------\r\n"+ EventLogEntryType.Error);
                        }
                    }
     
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);                
                }
            }
    Voila en espérant que ça en aidera d'autre.

    A+

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Mauvaise interpretation header avec smtp exchange 2010
    Par trezeled dans le forum Autres Solutions d'entreprise
    Réponses: 0
    Dernier message: 12/11/2013, 16h37
  2. [Exchange 2010] mailbox room
    Par kyuubi6 dans le forum Exchange Server
    Réponses: 0
    Dernier message: 08/03/2013, 15h22
  3. Messagerie unifiée avec Exchange 2010 SP1 et OCS 2007 R2
    Par Michaël dans le forum Articles
    Réponses: 0
    Dernier message: 29/09/2010, 22h51

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo