Trying w/o success to execute a PowerShell script from C#
I am trying to execute a PowerShell script to enable mailboxes on a Exchange 2010. The actual email account creation application is a Java servlet running on a Tomcat server ancd the servlet does most of the work validating the request and populating various system with the account info, including ActiveDirectory. Cutting to the chase, I wrote a service that listens for requests (generated by the servlet) that contains two lines of data, the user name and the database. The error message returned is:
Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.
This is the code:
Code:
private void run()
{
String inString;
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
StreamWriter writer = new StreamWriter(ns);
StreamReader reader = new StreamReader(ns);
Command myCommand = new Command(scriptFile);
// create and open Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
try
{
while (true)
{
inString = reader.ReadLine().Trim();
if (inString.Equals("eot",
StringComparison.CurrentCultureIgnoreCase))
break;
eventLog.WriteEntry(inString);
String[] parms = inString.Split(':');
CommandParameter testParam = new CommandParameter(parms[0], parms[1]);
myCommand.Parameters.Add(testParam);
}
}
catch (Exception e)
{
eventLog.WriteEntry(e.Message);
}
pipeline.Commands.Add(myCommand);
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
writer.WriteLine(stringBuilder.ToString());
writer.Flush();
ns.Close();
client.Close();
}
}
This is the PowerShell script that the Echange admin wrote for me:
Code:
param([string]$username,[string]$database)
$sess = New-PSSession -Configurationname Microsoft.Exchange -ConnectionUri http://mail.wfo.linfield.edu/powershell
Import-PSSession -session $sess
enable-Mailbox -DomainController fenrir.catnet.wfo.linfield.edu -identity $username -database $database
Any ideas about what wrong?
Rob Tanner
Linfield College