简体   繁体   English

创建属性get-mailbox cmdlet时使用Office365 a / c连接到联机交换时出错

[英]Error connect to exchange online using of Office365 a/c whencreated property get-mailbox cmdlet

Error : The WinRM client cannot complete the operation within the time spe cified. 错误:WinRM客户端无法在指定的时间内完成操作。 Check if the machine name is valid and is reachable over the network and firewall exception for Windows Remote Management service is enabled. 检查计算机名称是否有效并且可以通过网络访问,并且启用了Windows远程管理服务的防火墙例外。 Error number: -2144108250 错误编号:-2144108250

ps1 code: ps1代码:

param
(
[Parameter(Mandatory=$true)][System.Management.Automation.PSCredential]$credentials
)

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $credentials -Authentication Basic –AllowRedirection
Import PSSession $Session
Get-Mailbox

C# code: C#代码:

PSCredential credential;
private Runspace runspace;
private string UserName = ConfigurationManager.AppSettings["office365username"];
private string Password = ConfigurationManager.AppSettings["office365password"];

internal PSHelper()
{
    //Create the object of PSCredentials class
    credential = new PSCredential(this.UserName, CreateSecurePassword(this.Password));
    InitialSessionState SessionState = InitialSessionState.CreateDefault();
    SessionState.ImportPSModule(new[] { "MSOnline" });
    InitialSessionState Session = InitialSessionState.CreateDefault();
    SessionState.ImportPSModule(new[] { "PSSession" });
    //Create new runspace
    runspace = RunspaceFactory.CreateRunspace(SessionState);
    runspace.Open();
}

public GetRecentUsersCountResponse GetRecentUserCount()
{
    GetRecentUsersCountResponse Response = new GetRecentUsersCountResponse();
    try
    {

    int CountValue = 0;
    DateTime BeginDateForWeek;
    DateTime EndDateForWeek;
    string script = ReadPowerShellScript("GetRecentUserCount.ps1");
    Command cmd = new Command(script, true);
    cmd.Parameters.Add(new CommandParameter("credentials", credential));
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(cmd);
    pipeline.Input.Close();
    Collection<PSObject> collectionPSObject = pipeline.Invoke();
    if (collectionPSObject.Count > 0)
    {
        foreach (PSObject itemUser in collectionPSObject)
        {
            //check if the user if licensed,IsActive,WhenCreated
            if (itemUser.Properties["IsLicensed"] != null && itemUser.Properties["IsActive"] != null && itemUser.Properties["WhenCreated"] != null)
            {
                if (Convert.ToBoolean(itemUser.Properties["IsLicensed"].Value) && Convert.ToBoolean(itemUser.Properties["IsActive"].Value) && itemUser.Properties["WhenCreated"] != null)
                {
                    BeginDateForWeek = DateTime.Now;
                    EndDateForWeek = Convert.ToDateTime(itemUser.Properties["WhenCreated"].Value);
                    TimeSpan DifferenceofWeekDate = BeginDateForWeek - EndDateForWeek;
                    int DiffernceofDays = Convert.ToInt32(DifferenceofWeekDate.Days);
                    //Count only if  recently created users from last 7 days
                    if (DiffernceofDays <= 30)
                    {
                        CountValue++;
                    }

                }

            }
        }
    }
    pipeline.Stop();
    if (pipeline.Error.Count > 0)
    {
        StringBuilder builder = new StringBuilder();

        foreach (object item in pipeline.Error.ReadToEnd())
        {
            builder.Append(item.ToString());
            builder.Append(" - ");
        }
        Response.ErrorMessage = builder.ToString();
    }

    if (CountValue <= 7)
    {
        Response.RecentUserCountWeek = CountValue;
    }

    if (CountValue <= 30)
    {
        Response.RecentUserCountMonth = CountValue;
    }
    }

    catch (Exception ex)
    {
    Response.ErrorMessage = ex.Message;
    }
    finally
    {
    runspace.Dispose();
    }
    //return Response;
    return Response;
}

I want to connect to exchange and return the recent users from past 7 and 30 days. 我想连接交流并返回过去7天和30天的最近用户。

I've developed a powershell script that I run to do this. 我已经开发了一个Powershell脚本来执行此操作。 You can also change the WhenCreated attribute to another date attribute if needed. 如果需要,还可以将WhenCreated属性更改为另一个日期属性。 I usually run the commands to remote in separately with these commands 我通常将命令与这些命令分开远程运行

$cred = Get-Credential
(enter full email address and password)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange 
  -ConnectionUri https://ps.outlook.com/powershell/ 
  -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $Session

But you could put them in your script if you want. 但是您可以根据需要将它们放在脚本中。 I usually run this script manually. 我通常手动运行此脚本。 You just need to change the number of days (make sure it stays negative), put in the correct file path and add any other attributes you want to get. 您只需要更改天数(确保它保持负数),输入正确的文件路径并添加要获取的任何其他属性即可。

$fpath = "c:\users\(currentuser)\desktop\UserCreateDates.csv"
$numdays = -30

$logfilePath = (Test-Path $fpath)
if (($logFilePath) -ne "True")
{
    New-Item $fpath -ItemType File
    Add-Content $fpath "Name,EmailAddress,Created"
}
else
{
    Clear-Content $fpath
    Add-Content $fpath "Name,EmailAddress,Created"
}

$date1 = [DateTime]::Today.AddDays($numdays)
$Mailboxes = Get-Mailbox -ResultSize Unlimited -filter {RecipientType -eq "UserMailbox"} 

ForEach ($Mailbox In $Mailboxes) {
$DisplayName = """" + $Mailbox.DisplayName + """"
$UPN = """" + $Mailbox.UserPrincipalName + """"
$mailboxCreated = $Mailbox.WhenCreated
if ($mailboxCreated -gt $date1)
    {
        $DisplayName + "," + $UPN + ",""" + 
        $mailboxCreated + """" | Out-File -FilePath $fpath -Append
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#中使用ews获取邮箱属性(类似于Get-Mailbox run cmdlet的输出,但使用ews) - How to obtain properties of mailbox using ews in C# (similar to the output of Get-Mailbox run cmdlet but using ews) Office 365 Exchange邮箱属性 - Office 365 Exchange Mailbox Properties 如何使用兑换连接到Office 365邮箱 - How to connect to Office 365 mailbox using redemption 使用 .Net C# IMAP 客户端从 Exchange Server 读取 Office365 电子邮件 - Read Office365 emails from Exchange Server using .Net C# IMAP client 如何获得用户的交换/ outlook / office365照片? - How to get user's exchange/outlook/office365 photo? 使用 Exchange web 服务读取 Office 365 邮箱 - Read an office 365 mailbox using Exchange web services 使用RunspacePool的C#PowerShell - 如何导入像Get-Mailbox这样的Exchange Cmdlet? - C# PowerShell with RunspacePool - How to import Exchange Cmdlets like Get-Mailbox? 我可以使用单个 URL 在线访问 Exchange (office365) 吗? - Can I use a single URL to access Exchange online (office365)? 使用 PowerShell cmdlet 使用加密密码的密钥连接到 C# 中的 Exchange Online - Connect to Exchange Online in C# with PowerShell cmdlet using a key on encrypted password 在C#.Net中从Office365获取约会 - Get appointment from Office365 in C#.Net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM