我正在尝试向Exchange服务器添加别名集合。这只能通过Powershell cmdlet完成。 由于Microsoft在powershell下有包装器,并且只能在运行空间中进行分布式调用,因此我使用System.Management.Automation实用程序。 添加别名的命令如下所示:
Set-Mailbox -Identity john@contoso.com -EmailAddresses @{add=”john@northamerica.contoso.com”}
其中Set-Mailbox是一个命令,所有其他字段都是参数,而@add表示我们将新元素添加到现有集合。
由于Exchange运行空间在PSLanguageMode.NoLanguage模式下运行,因此只能执行Command而不能执行Scripts。通过这种方法,异常上升了:
Command addAliasCommand = new Command("Set-Mailbox -Identity john@contoso.com -EmailAddresses @{add=”john@northamerica.contoso.com”}", true);
只能执行带参数的清除命令:
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();
}
答案 0 :(得分:2)
@{ add = "john@northamerica.contoso.com" }
实际上是一个Hashtable @{ key = value }
结构,所以你可以这样做:
Command addAliasCommand = new Command("Set-Mailbox", true);
addAliasCommand.Parameters.Add("identity", "john@contoso.com");
var addresses = new Hashtable();
addresses.Add("add", "john@northamerica.contoso.com");
addAliasCommand.Parameters.Add("EmailAddresses", addresses);
答案 1 :(得分:0)
我添加了同样的问题。我最终使用了这个:
var pipeline = runspace.CreatePipeline();
string cmdAlias = "Set-Mailbox " + username + "@" + domainName + " -EmailAddresses @{Add='" + username + "@" + domainNameAlias + "'}";
pipeline.Commands.AddScript(cmdAlias);
pipeline.Invoke();