C#Powershell管道foreach-object [英] C# Powershell Pipeline foreach-object
问题描述
我有此PowerShell命令可将成员添加到Exchange Online中的分发组.这在PS中可以正常工作.但是我需要从C#应用程序执行此操作.
I have this PowerShell command to add members to a Distributon Group in Exchange Online. This works correctly in PS. But I need to do this from a C# app.
$arr | foreach-object{Add-DistributionGroupMember -Identity 'Test' -Member $_}
我需要将包含成员的数组传递给PS中的$ arr,并将其通过管道传递给foreach-object.我做了很多搜索,但是所有示例仅显示了如何执行单个命令.在C#中如何执行PS命令?
I need to pass an array containing the members to the $arr in PS and pipe it to the foreach-object. I have done a lot of searching but all the examples show only how to do single a command. How do the PS command in C#?
代码段:
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
string[] members = new string[] { "testuser1@somecompany.com",
"testuser2@somecompany.com",
};
ps.Commands.AddParameter("Members").AddArgument(members); // ??
ps.Commands.AddCommand("foreach-object"); // I'm stuck at this point
Collection<PSObject> results = ps.Invoke();
}
}
注意:由于远程脚本在我们的PS中被阻止,因此我无法通过 AddScript 来执行此操作.另外,由于运行空间仅执行第一个管道,因此无法执行以下操作.
Note:I can't do this via AddScript as remote scripts are blocked in our PS. Also doing something like below doesn't work as the runspace executes only the first pipeline.
foreach(string mem in members)
{
Command command = new Command("Add-DistributionGroupMember");
command.Parameters.Add("Identity", "test");
command.Parameters.Add("Member", member);
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(command);
pipeline.Invoke();
}
推荐答案
是的,该文档一直缺乏.我鞭打了下面.显然不是最好的,但似乎可以在 get-process
上工作(我无法尝试使用 Add-DistributionGroupMember
).您可能可以对此进行改进:
Yeah the documentation has been lacking. I whipped up the below. Clearly not the best, but seemed to work on get-process
( I cannot try out with Add-DistributionGroupMember
). You can probably improve upon it:
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
var members = new[]
{
"testuser1@somecompany.com",
"testuser2@somecompany.com",
};
var command1 = new Command("write-output");
command1.Parameters.Add("InputObject", members);
ps.Commands.AddCommand(command1);
foreach (PSObject output in ps.Invoke())
{
ps.Commands.Clear();
var command2 = new Command("Add-DistributionGroupMember");
ps.Commands.AddCommand(command2);
ps.Commands.AddParameter("Name", output);
ps.Commands.AddParameter("Identity", "test");
foreach (PSObject output2 in ps.Invoke())
{
Console.WriteLine(output2);
}
}
}
这篇关于C#Powershell管道foreach-object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!