Объединение сценария PowerShell для получения списка MailboxName, PrimarySMTPAddress, Кто получил доступ, AccessPermissions и SizeInMB - PullRequest
0 голосов
/ 05 сентября 2018

Я хочу изменить сценарий PowerShell, чтобы экспортировать список UserMailbox с доступом «Полный делегат» более чем одному человеку, кроме самого пользователя.

Следующий скрипт как-то возвращает результат:

Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox | 
Get-MailboxPermission | 
Where-Object { ($_.AccessRights -like "*FullAccess*") -and 
               (-not $_.IsInherited) -and 
               ($_.User -ne "NT AUTHORITY\SELF") -and 
               ($_.User -notlike '*Discovery Management*') } |
    Select @{Name="User Name";expression={(Get-Recipient $_.User.tostring()).displayname}}, 
            Identity,
            @{Name='Access Rights';Expression={[string]::join(', ', $_.AccessRights)}},
            @{Name="PrimarySMTPAddress";expression={(Get-Recipient $_.User).PrimarySMTPAddress}} | 
        Export-Csv -path C:\EE\Results.csv -NoTypeInformation

и

$filter = '(Enabled -eq $false) -and (msExchRecipientTypeDetails -ne 4) -and (homeMDB -ne "$null")'
$properties = @('homeMDB', 'mailNickName', 'mail', 'DisplayName', 'SamAccountName', 'ProxyAddresses')

Get-ADUser -Filter $filter -Properties $properties  |
    ForEach-Object {
        $stat = Get-MailboxStatistics $_.SamAccountName

        $smtpAddresses = ($_.ProxyAddresses | Where-Object {$_ -like "*smtp:*" }) -replace 'smtp:'

        New-Object -TypeName PSObject -Property ([ordered]@{
            DisplayName    = $_.DisplayName
            mailNickName   = $_.mailNickName
            SamAccountName = $_.SamAccountName
            mail           = $_.mail
            ProxyAddresses = $smtpAddresses -join ';'
            HomeMDB        = $_.homeMDB.Split(',=')[1]
            MBytes         = $stat.TotalItemSize.Value.ToMB()
            LastLogonTime  = $stat.LastLogonTime
            LastLoggedOnUserAccount = $stat.SamAccountName
            DisconnectDate = $stat.DisconnectDate
        })
    } | 
    Sort-Object MBytes -Descending | 
    Export-Csv C:\EE\Results.csv -NoTypeInformation

Но мне нужна помощь в изменении дополнительных столбцов, чтобы оно показывало:

  • Почтовый ящик пользователя с множественным полным делегированным доступом: в этом столбце будет отображаться отображаемое имя почтового ящика, к которому имеют доступ несколько пользователей. (Только отображаемое имя)

  • Основной SMTP-адрес: в этом столбце будет показан PrimarySMTPAddress первого столбца (Identity) или адрес электронной почты почтового ящика в первом столбце.

  • Кто получил доступ: в этом столбце отображаются имена пользователей, у которых есть UserMailbox (отображаемое имя).

  • Права доступа: показывает права доступа делегатов. [Это уже правильно]

  • Размер в МБ: в этом столбце будет показан размер почтового ящика в столбце 1 в мегабайтах.

1 Ответ

0 голосов
/ 05 сентября 2018

Я думаю, это поможет вам:

$filter = '(Enabled -eq $false) -and (msExchRecipientTypeDetails -ne 4) -and (homeMDB -ne "$null")'
$properties = @('homeMDB', 'mailNickName', 'mail', 'DisplayName', 'SamAccountName', 'ProxyAddresses')

Get-ADUser -Filter $filter -Properties $properties  |
    ForEach-Object {
        $stat = Get-MailboxStatistics $_.SamAccountName

        $smtpAddresses = ($_.ProxyAddresses | Where-Object {$_ -match "^smtp:" }) -replace 'smtp:', ''

        # Normally, the 'mail' attribute of a user is set to be the Primary email address, but
        # this need not be the case, as Exchange uses the ProxyAddresses attribute.
        # The PrimarySMTPAddress can be extracted from the ProxyAddresses with:
        $primarySmtpAddress = ($_.ProxyAddresses | Where-Object {$_ -cmatch "^SMTP:" }) -replace 'SMTP:', ''
        # or by using the EmailAddress property from the user object. 
        # You will then need to add 'EmailAddress' to the '$properties' array above  
        # $primarySmtpAddress = $_.EmailAddress

        # See if there are delegate users and what access rights they have
        $delegates = @(Get-MailboxPermission -Identity $primarySmtpAddress | 
                       Where-Object { ($_.AccessRights -like "*FullAccess*") -and 
                                      (-not $_.IsInherited) -and 
                                      ($_.User -ne "NT AUTHORITY\SELF") -and 
                                      ($_.User -notlike '*Discovery Management*') } |
                       Select-Object @{Name='Delegate'; Expression={(Get-Recipient $_.User.toString()).DisplayName}}, 
                                     @{Name='AccessRights';Expression={$_.AccessRights -join ', '}})

        ##############################################################################
        # The resulting $delegates is an array, so if you want to only get output for 
        # mailboxes that actually HAVE delegate users, you can uncomment the next line
        ##############################################################################

        # if ($delegates.Count -eq 0) { continue }

        # this can become a LONG column if you want to see the accessrights per user..
        $access = $delegates | ForEach-Object { "{0} ({1})" -f $_.Delegate, ($_.AccessRights -join ', ') }

        New-Object -TypeName PSObject -Property ([ordered]@{
            DisplayName             = $_.DisplayName
            mailNickName            = $_.mailNickName
            SamAccountName          = $_.SamAccountName
            mail                    = $_.mail
            PrimarySMTPAddress      = $primarySmtpAddress
            ProxyAddresses          = $smtpAddresses -join ';'
            HomeMDB                 = $_.homeMDB.Split(',=')[1]
            MBytes                  = $stat.TotalItemSize.Value.ToMB()
            LastLogonTime           = $stat.LastLogonTime
            LastLoggedOnUserAccount = $stat.SamAccountName
            DisconnectDate          = $stat.DisconnectDate
            Delegates               = $delegates.Delegate -join ', '        
            AccessRights            = $access -join ', '
        })
    } | 
    Sort-Object MBytes -Descending | 
    Export-Csv C:\EE\Results.csv -NoTypeInformation
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...