简体   繁体   中英

Disable ActiveSync using C#

I am trying to use C# to disable ActiveSync mailboxes on Exchange Server 2007 (and soon to be 2013 which is probably completely different) using powershell. The first command works to set the Allowed Device IDs. The second to turn off activesync does not. Am I specifying it incorrectly?

RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();

PSSnapInException PSException = null;
PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out PSException);

Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);

runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();

Command command = new Command("Set-CASMailbox");

command.Parameters.Add("Identity", username);
command.Parameters.Add("ActiveSyncAllowedDeviceIDs", "\"BLOCKED\"");
pipeline.Commands.Add(command);

command = new Command("Set-CASMailbox");
command.Parameters.Add("Identity", username);
command.Parameters.Add("ActiveSyncEnabled", false);

pipeline.Commands.Add(command);

Collection<PSObject> result = pipeline.Invoke();

I don't have much experience with C# and PowerShell or the Exchange PS cmdlets for that matter, so I might be wrong here.

AFAIK your sample would equal:

Set-CASMailbox -Identity 'User1' -ActiveSyncAllowedDeviceIDs "BLOCKED" | Set-CASMailbox -Identity 'User1' -ActiveSyncEnabled $false

You're not using the object (if any) that the first cmdlet returns, so they don't belong in a pipeline. You should run them separately, like:

Set-CASMailbox -Identity 'User1' -ActiveSyncAllowedDeviceIDs "BLOCKED"
Set-CASMailbox -Identity 'User1' -ActiveSyncEnabled $false

In C# I guess you need to call Invoke() twice.

Pipeline pipeline = runspace.CreatePipeline();

Command command = new Command("Set-CASMailbox");
command.Parameters.Add("Identity", username);
command.Parameters.Add("ActiveSyncAllowedDeviceIDs", "BLOCKED");
pipeline.Commands.Add(command);

//Run first cmdlet
Collection<PSObject> result = pipeline.Invoke();

//Not sure how to reset. Create new pipeline?
Pipeline pipeline2 = runspace.CreatePipeline();

Command command2 = new Command("Set-CASMailbox");
command2.Parameters.Add("Identity", username);
command2.Parameters.Add("ActiveSyncEnabled", false);
pipeline2.Commands.Add(command);

//Run second cmdlet
Collection<PSObject> result2 = pipeline2.Invoke();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM