问题
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???
回答1:
You can simply use LINQ:
result.Where(p => (string)p.Properties["Server"].Value == "myserver"));
回答2:
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:
//Getting all command variables
string myServer = "ServerName";
//Create Script command
String customScriptText = String.Format("Get-MailboxDatabase -IncludePreExchange2007 -Status | Where-Object {{$_.Server -eq \"{0}\"}}", myServer);
pipeline.Commands.AddScript(customScriptText);
Note to escape { and }
using double curly braces i.e. {{
and }}
. Also escape quotes as \"
using back slash in the String.Format method.
来源:https://stackoverflow.com/questions/14104222/powershell-whereobjectcommand-from-c-sharp