Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private Runspace runspace;
- private void RunSharedMailboxScript()
- {
- string organizationalUnit = GetOrganizationalUnitName(sharedMailboxOrganizationalUnitCombobox.SelectedIndex);
- string mailboxUPN = "$mailbox_alias@afconsult.com";
- string newMailBoxScript = $@"New-Mailbox -Name {sharedMailboxNameTextbox.Text} -Alias {sharedMailboxAliasTextbox.Text} -OrganizationalUnit {organizationalUnit} -UserPrincipalName {mailboxUPN} -Shared";
- string addADGroupMemberScript = $@"Add-ADGroupMember 'Office 365 Users' -Members {sharedMailboxAliasTextbox.Text}";
- string setADUserScript = $@"Set-ADUser $mailbox_alias -Description '{sharedMailboxIncidentNumberTextbox.Text} - {DateTime.Now.ToString()}'";
- RunConnectToExchangeScript();
- RunScript(newMailBoxScript);
- RunScript(addADGroupMemberScript);
- RunScript(setADUserScript);
- CloseExchangeScript();
- }
- private void RunConnectToExchangeScript()
- {
- string exchangeHostname = "http://afsesthex10.af.se/powershell/";
- // Get credentials
- string userName = connectToExchangeUsernameBox.Text;
- SecureString password = connectToExchangePasswordbox.SecurePassword;
- PSCredential Credential = new PSCredential(userName, password);
- // Set the connection info
- WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(exchangeHostname), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", Credential);
- {
- connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
- }
- runspace = RunspaceFactory.CreateRunspace();
- PowerShell powershell = PowerShell.Create();
- PSCommand command = new PSCommand();
- command.AddCommand("New-PSSession");
- command.AddParameter("ConfigurationName", "Microsoft.Exchange");
- command.AddParameter("ConnectionUri", exchangeHostname);
- command.AddParameter("Credential", Credential);
- command.AddParameter("Authentication", "Kerberos");
- // -AllowRedirection
- powershell.Commands = command;
- // Open the runspace
- runspace.Open();
- // Associate the runspace with powershell
- powershell.Runspace = runspace;
- // Invoke the powershell to obtain results
- Collection<PSSession> result = powershell.Invoke<PSSession>();
- foreach (ErrorRecord current in powershell.Streams.Error)
- Console.WriteLine(String.Format($"The following Error happen when opening the remote Runspace: {0} | InnerException: {1}", current.Exception, current.Exception.InnerException));
- Console.ReadLine();
- if (result.Count != 1)
- throw new Exception("Unexpected number of runspace connections returned.");
- }
- private void CloseExchangeScript()
- {
- runspace.Close();
- }
- private void RunScript(string script)
- {
- Pipeline pipeline = runspace.CreatePipeline();
- pipeline.Commands.AddScript(script);
- pipeline.Invoke();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement