ASP.NET MVC / C# : run exchange remote PowerShell code doesn't remove relay entry

Viewed 109

I got an ASP.NET MVC app that launches an Exchange Server powershell script, that add and remove smtp relay entries.

Runspace runspace = RunspaceFactory.CreateRunspace();

PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();

command.AddCommand("New-PSSession");

command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", uri);                
command.AddParameter("Authentication", "Default");
powershell.Commands = command;

runspace.Open(); 
powershell.Runspace = runspace;

Collection<PSSession> result = powershell.Invoke<PSSession>();

powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Set-Variable");
command.AddParameter("Name", "ra");
command.AddParameter("Value", result[0]);

powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();

powershell = PowerShell.Create();
command = new PSCommand();
command.AddScript("Import-PSSession -Session $ra");
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();

powershell.AddScript(@"$connector = Get-ReceiveConnector 'Mail-01\Client FrontEnd Relay for Printer and Clients' ");
powershell.AddScript(@"$connector.remoteipranges += '" + entry + "'");
powershell.AddScript(@"Set-ReceiveConnector 'Mail-01\Client FrontEnd Relay for Printer and Clients' -RemoteIPRanges $connector.remoteipranges");
powershell.Invoke();

This example adds a relay entry and this works.

If I try the same code with "-=" the entry doesn't get removed from the smtp relay.

powershell.AddScript(@"$connector.remoteipranges -= '" + entry + "'");

When I run this script code on the same machine in powershell directly the entry is removed from the smtp relay.

Can any Exchange guru here help me?

regards

0 Answers
Related