我有一个简单的控制台应用程序,试图通过 PowerShell 在 Exchange 中创建一个通讯组并向其中添加一些成员。
class Program
{
static void Main(string[] args)
{
string userName = "foo";
string password = "pwd";
// Encrypt password using SecureString class
SecureString securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
PSCredential credential = new PSCredential(userName, securePassword);
// Connection information object required to connect to the service
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
new Uri("https://ps.outlook.com/powershell"),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",
credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.MaximumConnectionRedirectionCount = 2;
// Create runspace on remote Exchange server
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using(PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
Command newDG = new Command("New-DistributionGroup");
newDG.Parameters.Add(new CommandParameter("Name", "Test"));
ps.Commands.AddCommand(newDG);
Command addDGMember1 = new Command("Add-DistributionGroupMember");
addDGMember1.Parameters.Add(new CommandParameter("Identity", "Test"));
addDGMember1.Parameters.Add(new CommandParameter("Member", "testuser1@somecompany.com"));
ps.Commands.AddCommand(addDGMember1);
Command addDGMember2 = new Command("Add-DistributionGroupMember");
addDGMember2.Parameters.Add(new CommandParameter("Identity", "Test"));
addDGMember2.Parameters.Add(new CommandParameter("Member", "testuser2@somecompany.com"));
ps.Commands.AddCommand(addDGMember2);
try
{
// Invoke command and store the results in a PSObject
Collection<PSObject> results = ps.Invoke();
if (ps.Streams.Error.Count > 0)
{
foreach (ErrorRecord error in ps.Streams.Error)
{
Console.WriteLine(error.ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Operation completed.");
}
}
}
Console.ReadKey();
}
}
当我运行我的应用程序时,它会引发此错误:输入对象无法绑定到命令的任何参数,因为命令不接受管道输入,或者输入及其属性与接受管道输入的任何参数都不匹配。
但实际上是创建了通讯组。
另外,我注意到,当我注释掉创建新通讯组的命令并运行添加通讯组成员的命令时,只添加了第一个成员。我真的很困惑我应该如何处理这个问题,我有以下问题:
如何让我的代码成功运行所有命令?
执行多个远程 PowerShell 命令的最佳方法是什么?我是否分别运行每个命令,检查返回对象是否成功,然后继续执行下一个命令。有什么性能问题需要注意吗?
运行空间一次只运行一个命令吗?
当我尝试以下代码时,我遇到了这个错误: 这个运行空间不支持语法。这可能是因为它处于无语言模式。
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using(PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
Pipeline pipe = runspace.CreatePipeline();
pipe.Commands.AddScript("New-DistributionGroup -Name Test2");
try
{
Collection<PSObject> results = pipe.Invoke();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}