Search code examples
c#powershellexchange-server-2010

Add Powershell commands to the pipeline


I'm trying to get the lower store from a 2010 Exchange server, and the function will run in a WCF container.

The problem I'm facing is that I'm unable to run multiple PowerShell commands in the pipeline.

I've tried the following (based on this, how to invoke the powershell command with "format-list" and "out-file" pipeline from c#?):

string strCommand = @"Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize | Sort-Object DatabaseSize";
string CommandLine = string.Format("&{{{0}}}", strCommand);
pipeLine.Commands.AddScript(CommandLine);

But I get:

Unhandled Exception: System.Management.Automation.RemoteException: Script block literals are not allowed in restricted language mode or a Data section.

Also I tried,

Command getMailbox = new Command("Get-MailboxDatabase");
getMailbox.Parameters.Add("Status", null);

Command sort = new Command("Sort-Object");

pipeLine.Commands.Add(getMailbox);
pipeLine.Commands.Add(sort);

Collection<PSObject> commandResults = pipeLine.Invoke();

But not luck:

Unhandled Exception: System.Management.Automation.RemoteException: The term 'Sort-Object' is not recognized as the name of a cmdlet

I wonder if I should use multiple pipelines (one pipeline per cmdlet), but I am not sure.


Solution

  • It sounds like the problem is the runspace. If that's an Exchange server, and you're running that in the remote management session provided by Exchange, the only thing you can do in that session is run the Exchange cmdlets. The Select-Object and Sort-Object cmdlets and other PowerShell language elements just aren't there to use.