Invoke PowerShell with parameters from C#

In this example, I’m using PowerShell script to connect to Exchange Server and create a mailbox. The parameters include the credentials that’ll be passed from C# while calling the script.

Below is the PowerShell script:

Invoke-Command -ComputerName  -Credential $creds -ScriptBlock {
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://{serverdns}/PowerShell/ -Authentication Kerberos -Credential $using:creds
Import-PSSession $s
$securePassword = ConvertTo-SecureString $using:pwd -AsPlainText -Force
new-mailbox -UserPrincipalName $using:UPN -Alias $using:alias -Database $using:database -Name $using:cName -SamAccountName $using:sAMAccountName -OrganizationalUnit $using:OU -Password $securePassword -FirstName $using:fName -LastName $using:lName -DisplayName $using:displayName -ResetPasswordOnNextLogon $true

The C# code below will invoke the above PowerShell script:

using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;

public string CreateMailbox(Int64 requestID, int sID, string cName, string firstName, string lastName, string displayName, string UPN, string alias, string exchangeDatabase, string userName, string OU, string accountPassword)
	Uri uri = new Uri(exch.ExchangeServer);
	SecureString secureExchangePassword = String2SecureString(exch.ExchangePassword);

	PSCredential credentials = new PSCredential(exch.ExchangeUserName, secureExchangePassword);

	Runspace runspace = RunspaceFactory.CreateRunspace();

	Collection<PSObject> results = new Collection<PSObject>();

	PowerShell powershell = PowerShell.Create();

		powershell.Runspace = runspace;

		//Change the Path to the Script to suit your needs
		System.IO.StreamReader sr = new System.IO.StreamReader("Script\\MailboxScript.ps1");

		powershell.Runspace.SessionStateProxy.SetVariable("creds", credentials);
		powershell.Runspace.SessionStateProxy.SetVariable("cName", cName);
		powershell.Runspace.SessionStateProxy.SetVariable("fName", firstName);
		powershell.Runspace.SessionStateProxy.SetVariable("lName", lastName);
		powershell.Runspace.SessionStateProxy.SetVariable("UPN", UPN);
		powershell.Runspace.SessionStateProxy.SetVariable("alias", alias);
		powershell.Runspace.SessionStateProxy.SetVariable("database", exchangeDatabase);
		powershell.Runspace.SessionStateProxy.SetVariable("sAMAccountName", userName);
		powershell.Runspace.SessionStateProxy.SetVariable("OU", OU);
		powershell.Runspace.SessionStateProxy.SetVariable("password", accountPassword);
		powershell.Runspace.SessionStateProxy.SetVariable("displayName", displayName);

		results = powershell.Invoke();
		if (powershell.Streams.Error.Count > 0)
			StringBuilder sb = new StringBuilder();
			foreach (ErrorRecord er in powershell.Streams.Error)
				sb.Append(er.ToString() + "       ");

			LogFactory.LogError("RequestID:'" + requestID.ToString() + "' ID:'" + sID.ToString() + "' Error:  On creating exchange account(PowerShell). Reason: " + sb.ToString());
			return "";
			return String.Concat("CN=" + cName + ",", OU);
	catch (Exception ex)
		LogFactory.LogError("RequestID:'" + requestID.ToString() + "' ID:'" + sID.ToString() + "' Error:  While creating exchange account. Reason: " + ex.Message.ToString());
		return "";
		runspace = null;

private SecureString String2SecureString(string password)
	SecureString remotePassword = new SecureString();
	for (int i = 0; i < password.Length; i++)

	return remotePassword;

This C# code can be called from an Application passing the required Exchange Server information and required Parameter values. The using statements in the C# code mentions the required Nuget packages to be installed.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.