问题
How can I call Where-Object
(without filter) from C#? I can't parse output, because I want to pass it to pipeline(not in example below).
PS:
Get-MailboxPermission username | Where-Object {$_.AccessRights -match "FullAccess" -and $_.IsInherited -eq $False}
C#:
Collection<PSObject> results = null;
Command command1 = new Command("Get-MailboxPermission");
command1.Parameters.Add("Identity", mailbox);
command1.Parameters.Add("DomainController", _domainController);
//I cannot use Filter. This is not possible in PS also.
//command1.Parameters.Add("Filter", "AccessRights -match \"FullAccess\"");
This question is simmilar to: PowerShell WhereObjectCommand from C# That answer is not enough for my problem.
回答1:
Check the below code sample. I have updated a sample from code project here as per your requirements.
Note:
- To add quotes to your command i.e. script text escape quotes by using
\"
To add
{
or}
brace to the script text use double curly braces instead to escape it inside String.Format like{{
or}}
// create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); //Getting all command variables string computerName = "YourComputerName"; string matchingPattern = "con"; //Create Script command String customScriptText = String.Format("Get-Process -ComputerName {0} | Where-Object {{$_.ProcessName -match \"{1}\"}}", computerName,matchingPattern); pipeline.Commands.AddScript(customScriptText); // add an extra command to transform the script output objects into nicely formatted strings // remove this line to get the actual objects that the script returns. pipeline.Commands.Add("Out-String"); // execute the script Collection<PSObject> results = pipeline.Invoke(); // 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()); }
When you apply the above working sample to your problem you will need to change couple of lines like below:
//Getting all command variables
string username = "YourUserName";
//Create Script command
String customScriptText = String.Format("Get-MailboxPermission {0} | Where-Object {{$_.AccessRights -match \"FullAccess\" -and $_.IsInherited -eq $False}}", username);
来源:https://stackoverflow.com/questions/36796176/calling-powershells-where-object-from-c-sharp