Q:

Executing scripts with Powershell via C#

I need to execute the following script:
Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize
I tried a few solutions with Powershell and Command classes, but they doesn't work.
Error that I received:
Value parameters cannot be null.

A:

I think this will do what you're looking for:
private string RunLocalExchangePowerShell(string script)
{
    // create the runspace and load the snapin
    RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
    PSSnapInException snapInException = null;
    Runspace runSpace = RunspaceFactory.CreateRunspace(rsConfig);
    runSpace.Open();
    rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
    Pipeline pipeLine = runSpace.CreatePipeline();

    // load the script and convert the output to a string
    pipeLine.Commands.AddScript(script);
    pipeLine.Commands.Add("out-string");

    // get the results
    Collection<PSObject> results;
    results = pipeLine.Invoke();

    // loop through the results and build the output
    StringBuilder sb = new StringBuilder();
    foreach (PSObject obj in results)
    {
        sb.AppendLine(obj.ToString());
    }

    // close the pipeline and runspace
    pipeLine.Dispose();
    runSpace.Close();

    return sb.ToString();
}

Example usage:
Console.WriteLine(prog.RunLocalExchangePowerShell("Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize"));

