Reputation:
I have found guides that explain how to run PowerShell scripts on an Exchange Server, but all guides require that the machine is domain-joined, and most seem to use workarounds, rather than best practices.
Is there a way to remotely connect to an Exchange Server using either C#.NET or VB.NET?
Essentially, I want to connect to my Exchange Server using administrator credentials (I would supply them, encrypted, in the program), and create a mailbox using a PowerShell scriptlet. That is all.
I would like to start the application as a console application, and once I confirm functionality I can implement it into a web forms application or MVC.
Any advice is greatly appreciated!
Upvotes: 5
Views: 2600
Reputation: 8664
I had to deal with a similar issue recently, the below code helped me to perform the functionality with a secure connection to the remote Exchange server.
Runspace remoteRunspace = null;
PSCredential psc = null;
// If user name is not passed used the credentials of the current farm account
if (!string.IsNullOrWhiteSpace(username))
{
if (!string.IsNullOrWhiteSpace(domain))
username = domain + "\\" + username;
SecureString secpassword = new SecureString();
if (!string.IsNullOrEmpty(password))
{
foreach (char c in password)
{
secpassword.AppendChar(c);
}
}
psc = new PSCredential(username, secpassword);
}
WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(RemotePowerShellUrl), PowerShellSchema, psc);
if (psc != null)
rri.AuthenticationMechanism = AuthenticationMechanism.Credssp;
remoteRunspace = RunspaceFactory.CreateRunspace(rri);
remoteRunspace.Open();
Pipeline pipeline = remoteRunspace.CreatePipeline();
Command cmdSharePointPowershell = new Command(Commands.AddPSSnapin.CommandName);
cmdSharePointPowershell.Parameters.Add(Commands.AddPSSnapin.Name, MicrosoftSharePointPowerShellSnapIn);
pipeline.Commands.Add(cmdSharePointPowershell);
pipeline.Invoke();
Of course you will some usual configuration of the user group membership, server allowance of remote secure/insecure remote connection and so on. this article may help.
Upvotes: 6