I use the below code to connect to office365 and retrive mailbox information using c# with remote powershell.
strExchange2010PSURI = "https://ps.outlook.com/PowerShell-LiveID?PSVersion=3.0";
strAccountName = "[email protected]";
strAccountPwd = "ppp";
public DataTable GetMailboxes(string searchMailbox)
{
DataTable dt = null;
List<string> mailboxes = new List<string>();
Command psCmd1 = new Command("Get-Mailbox");
psCmd1.Parameters.Add(new CommandParameter("Identity", "*" + searchMailbox + "*"));
Collection<PSObject> psExchMailboxInfo = fnGetPSData(psCmd1, null);
if (psExchMailboxInfo != null && psExchMailboxInfo.Count > 0)
{
//logic to get the mailbox details in a datatable
dt = GetMailboxInfo(mailboxes);
}
return dt;
}
private Collection<PSObject> fnGetPSData(Command psCmd1, Command psCmd2)
{
Pipeline psPipeLine = null;
Runspace psRunSpace = null;
WSManConnectionInfo psConnInfo = null;
var varSecurePwd = new SecureString();
try
{
foreach (var c in strAccountPwd)
{
varSecurePwd.AppendChar(c);
}
PSCredential psCreds = new PSCredential(strAccountName, varSecurePwd);
psConnInfo = new WSManConnectionInfo(new Uri(strExchange2010PSURI), "Microsoft.Exchange", psCreds);
psConnInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
psRunSpace = RunspaceFactory.CreateRunspace(psConnInfo);
psRunSpace.Open();
psPipeLine = psRunSpace.CreatePipeline();
if (psCmd1 != null)
{
psPipeLine.Commands.Add(psCmd1);
}
if (psCmd2 != null)
{
psPipeLine.Commands.Add(psCmd2);
}
Collection<PSObject> psObjects = psPipeLine.Invoke();
return psObjects;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (psPipeLine != null && psPipeLine.Commands != null)
{
psPipeLine.Commands.Clear();
psPipeLine.Dispose();
}
if (psRunSpace != null)
{
psRunSpace.Close();
psRunSpace.Dispose();
}
}
}
It works in my development environment but when I try the same in production I get "Connecting to remote server ps.outlook.com failed with the following error message: Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.".
Can anyone help?