我正在尝试将别名集合添加到 Exchange 服务器。这只能通过 Powershell cmdlet 完成。由于微软在 powershell 下有包装器,并且分布式调用只能在运行空间中完成,我为此使用 System.Management.Automation 实用程序。添加别名的命令如下所示:
Set-Mailbox -Identity john@contoso.com -EmailAddresses @{add=”john@northamerica.contoso.com”}
其中 Set-Mailbox 是一个命令,所有其他字段都是参数,@add 表示我们将新元素添加到现有集合中。
由于 Exchange 运行空间在 PSLanguageMode.NoLanguage 模式下运行,因此只能执行命令,但不能执行脚本。使用这种方法会引发异常:
Command addAliasCommand = new Command("Set-Mailbox -Identity john@contoso.com -EmailAddresses @{add=”john@northamerica.contoso.com”}", true);
只能执行带参数的 clear 命令:
Command addAliasCommand = new Command("Set-Mailbox", true);
addAliasCommand.Parameters.Add("identity", "test@test.onmicrosoft.com");
addAliasCommand.Parameters.Add("EmailAddresses", "testing.alias10@test.onmicrosoft.com, testing.alias11@test.onmicrosoft.com");
但是这种方法的问题是,当我想添加/删除新别名时,它完全重写了别名集合。
问题是如何添加指针@Add 以显示这些值已添加到现有的ProxyAddressCollection 集合中?
完整代码:
System.Security.SecureString secureString = new System.Security.SecureString();
foreach (char c in Password)
secureString.AppendChar(c);
PSCredential credential = new PSCredential(AdminLogin, secureString);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://ps.outlook.com/PowerShell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 4;
IList<string> gmResults = null;
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (Pipeline plPileLine = runspace.CreatePipeline())
{
try
{
Command addAliasCommand = new Command("Set-Mailbox", true);
addAliasCommand.Parameters.Add("identity", "test@test.onmicrosoft.com");
addAliasCommand.Parameters.Add("EmailAddresses", "testing.alias10@test.onmicrosoft.com, testing.alias11@test.onmicrosoft.com");
var rsResultsresults = plPileLine.Invoke();
if (!string.IsNullOrEmpty(resultObjectName))
{
gmResults =
rsResultsresults.Select(obj => obj.Members[resultObjectName].Value.ToString()).ToList();
}
plPileLine.Stop();
}
catch (Exception e)
{
return null;
}
finally
{
runspace.Close();
runspace.Dispose();
}
}
runspace.Close();
}