我使用以下代码连接到office365并使用带远程PowerShell的c#来检索邮箱信息。
strExchange2010PSURI = "https://ps.outlook.com/PowerShell-LiveID?PSVersion=3.0";
strAccountName = "uuuu@kcstaff.onmicrosoft.com";
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();
}
}
}
它适用于我的开发环境但是当我在生产中尝试相同时,我得到“连接到远程服务器ps.outlook.com失败,并显示以下错误消息:访问被拒绝。有关详细信息,请参阅about_Remote_Troubleshooting帮助主题。 ”
有人可以帮忙吗?
答案 0 :(得分:0)
似乎认证机制不起作用。我会避免使用ConnInfo并在打开PSRunspace之后尝试这个:
Command PSCredentialCommand = new Command("Set-Variable");
PSCredentialCommand.Parameters.Add("Name", "PSCredentials");
PSCredentialCommand.Parameters.Add("Value", pscreds);
pipeline.Commands.Add(PSCredentialCommand);
pipeline.Commands.AddScript(script);
脚本内容如下:
$O365Session = New-PSSession -ConfigurationName 'Microsoft.Exchange' -ConnectionUri 'https://ps.outlook.com/powershell' -Credential $PSCredentials -Authentication 'Basic' -AllowRedirection
Import-PSSession $O365Session -AllowClobber | Out-Null
等