none
Powershell AD output with OU RRS feed

  • Question

  • Hello,

    I have an lastlogin powershell script that I'm trying to include the users OU. AD has around 30 OU's and I'd like to know which one each user is in. This is what I have so far, I'm not sure how to add it.

    $users = get-mailbox -organizationalunit "OU" -resultsize unlimited
    $userarray = @()
    foreach ($user in $users)
    {
    $MailUser = $user.UserPrincipalName
    $stats= Get-MailboxStatistics $MailUser
    $datetime = $stats.LastLogonTime
    $date, $time = $datetime -split(' ')
    $Maildetails = New-Object -TypeName PSObject -Property @{
    DisplayName = $stats.DisplayName
    ItemCount = $stats.ItemCount
    MailboxSize = $stats.TotalItemSize
    LastLogonDate = $date
    LastLogonTime = $time
    Email = $MailUser

    }

    $userarray += $Maildetails


    $userarray | Export-Csv -Path C:\Users1.csv


    Monday, July 6, 2020 6:33 PM

All replies

  • Assuming all your users are in Organizational Units and not Containers, try this:

    $OU = $stats.distinguishedname.Substring($stats.$distinguishedname.IndexOf('OU='))

    It avoids the problems usually introduced when you try to simply split the distinguished name on commas and you have a comma in the users Common Name (CN) or an OU component. It also avoids having to use regular expressions.


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Monday, July 6, 2020 7:00 PM
  • Yes they are. Where should I put that line? See below. I'm getting the errors.

    $users = get-mailbox -organizationalunit OU" -resultsize unlimited
    $userarray = @()
    foreach ($user in $users)
    {
    $MailUser = $user.UserPrincipalName
    $stats= Get-MailboxStatistics $MailUser
    $datetime = $stats.LastLogonTime
    $date, $time = $datetime -split(' ')
    $Maildetails = New-Object -TypeName PSObject -Property @{
    $OU = $stats.distinguishedname.Substring($stats.$distinguishedname.IndexOf('OU='))
    DisplayName = $stats.DisplayName
    ItemCount = $stats.ItemCount
    MailboxSize = $stats.TotalItemSize
    LastLogonDate = $date
    LastLogonTime = $time
    Email = $MailUser

    }

    $userarray += $Maildetails


    $userarray | Export-Csv -Path C:\Users3.csv

    Tuesday, July 7, 2020 12:11 AM
  • What errors?

    If it's what I think it might be, try this with the additional parentheses):

    $OU = ($stats.distinguishedname).Substring(($stats.$distinguishedname).IndexOf('OU='))
    I can't execute the code because I have no AD to run it against.


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Tuesday, July 7, 2020 1:53 AM
  • Hi Waldo129, just want to confirm the current situations. Have you got a chance to verify above suggestion? If the above reply is helpful please mark it as answer.

    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Friday, July 10, 2020 5:44 AM