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 コマンドを実行する最良の方法は何ですか? 各コマンドを個別に実行し、成功した場合は戻りオブジェクトを確認してから、次のコマンドに進みますか? 注意すべきパフォーマンスの問題はありますか?
実行空間は一度に 1 つのコマンドのみを実行しますか?
次のコードを実行しようとすると、次のエラーが発生します: The syntax is not supported by this runspace. これは、非言語モードになっていることが原因である可能性があります。
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);
}
}
}