I'm trying to call the following PS script from C#:
Get-MailboxDatabase -IncludePreExchange2007 -Status | Where-Object {$_.Server -eq 'myserver'}
I have managed to execute the first part before the pipe using this code:
public void Test()
{
using (Pipeline pipeline = _runspace.CreatePipeline())
{
var cmd1 = new Command("Get-MailboxDatabase");
cmd1.Parameters.Add("IncludePreExchange2007");
cmd1.Parameters.Add("Status");
var cmd2 = new Command("Where-Object");
//how do I script {$_.Server -eq 'myserver'} ???
pipeline.Commands.Add(cmd1);
//pipeline.Commands.Add(cmd2);
Collection<PSObject> result = pipeline.Invoke();
}
}
but how do I script the second part for Where-Object???
I am updating this thread in case another user visits this question.
To enhance the performance you can perform filtering in the PowerShell itself and can use Where-Object there. I have provided the answer here: Calling PowerShell's where-object from C#
Essentially, you will need to use Add Script instead of adding command like below:
Note to escape
{ and }
using double curly braces i.e.{{
and}}
. Also escape quotes as\"
using back slash in the String.Format method.You can simply use LINQ: