Get-MailboxOwner

I used to have an old vbscript from Glen’s website that I modified so that it returns the username of the mailbox owner.

I didn’t notice until recently but it turns out that Glen has provided a version of his script in powershell as well as a GUI version.

With powershell V2 and the ActiveDirectory module things are even much easier. I’ve added also two features:

  • The ability to use wildcards in the MailboxName script parameter.
  • The ability to pass a username (SamAccountName) to the script instead of a mailboxname so that it enumerates all mailboxes rights and shows the mailboxnames where the given username has full control. I know it may really be time consuming depending on how many objects you have in your Active Directory. So, I’ve added a progress bar while searching.

Pls note also that I’ve hardcoded the maximum number of AD objects returned by the LDAP query to 10000. You may need to modify it…

#Requires -Version 2.0

<#
 
.SYNOPSIS    
    Search for mailbox owner by using a mailboxname or a username
 
.DESCRIPTION  
    Search for mailbox owner by using a mailboxname or a username

 
.PARAMETER MailboxName
    Displays who is the current owner on the mailbox

.PARAMETER UserName
    Displays which mailbox the UserName has been granted full control

.EXAMPLE    
    .\Get-MailboxOwner.ps1 -UserName $env:username

    Returns the mailbox names where the current user has full control

.EXAMPLE    
    .\Get-MailboxOwner.ps1 -MailboxName "test*"

    Returns the mailbox names and their owner. 
    Wildcard are allowed in the mailbox name.

.NOTES    
    Name: Get-MailboxOwner
    Author: Emin Atac
    DateCreated: 28/02/2012
 
.LINK    
    https://p0w3rsh3ll.wordpress.com

INPUTS
System.String

OUTPUTS
System.Management.Automation.PSCustomObject

#>


[CmdletBinding(DefaultParameterSetName='MBX', SupportsTransactions=$false)]
param(
   [Parameter(ParameterSetName='MBX', Mandatory=$true, ValueFromPipeline=$true, Position=0)]
   [system.string]${MailboxName},

   [Parameter(ParameterSetName='User', Mandatory=$true, ValueFromPipeline=$true, Position=0)]
   [system.string]${UserName}
)



function ConvertTo-Sid
{
<#
    
.SYNOPSIS    
    Translate a user name to a SID

.DESCRIPTION  
    Translate a user name to a SID

.PARAMETER Sid
    Provide a username

.NOTES    
    Name: ConvertTo-Sid
    Author: thepowershellguy
        
.LINK    
    http://thepowershellguy.com/blogs/posh/archive/2007/01/23/powershell-converting-accountname-to-sid-and-vice-versa.aspx
     
.EXAMPLE
    (ConvertTo-Sid "Domain\Administrator").Value
    Get the SID of the Active Directory Domain admininstrator

.EXAMPLE
    ConvertTo-Sid "Administrator"
    Get the SID of the local administrator account
#>

param(
[parameter(Mandatory=$true,Position=0)][system.string]$NtAccount = $null
)
 begin
 {
    $obj = new-object system.security.principal.NtAccount($NTaccount)
 } 
 process
 {
    try
    {
        $obj.translate([system.security.principal.securityidentifier])
    }
    catch
    {
        # To remove the silent fail, uncomment next line
        # $_
    }
 } 
 end
 {
 }
}

# First we load the Active Directory module as it's required
if ( (Get-Module -Name ActiveDirectory).Name -ne "ActiveDirectory")
{
Write-Host -ForegroundColor Yellow -Object "Attempting to load Active Directory module for Powershell"
Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue
    if ( (Get-PSDrive -PSProvider ActiveDirectory -ErrorAction SilentlyContinue).Name -ne "AD")
    {
     Write-Host -ForegroundColor Red -Object "Active Directory module for Powershell not loaded. Aborting"
     exit
    }
}

# Get the Primary Domain controller
$PDC  = (Get-ADDomainController  -Service 1 -Discover).Hostname

$results = @()

switch ($PsCmdlet.ParameterSetName)
{ 
    MBX {

        # Get the mailbox
        $all = Get-ADUser -Filter {(mailnickname -like $MailboxName)} -Properties mailnickname,msExchMailboxSecurityDescriptor -SearchScope 2 -Server "$PDC"
        
        foreach ($item in $all)
        {
            # The user who created the mailbox: $item.msExchMailboxSecurityDescriptor.Owner
            foreach ($ace in $item.msExchMailboxSecurityDescriptor.Access)
            {
                if ($ace.ActiveDirectoryRights -band [System.DirectoryServices.ActiveDirectoryRights]::CreateChild)
                {
                    # Make sure we have only user who are domain members
                    if ((ConvertTo-Sid $ace.IdentityReference.Value).Value -match "S-1-5-21-")
                    {
                        # We can skip inherited domain users
                        if (-not($Ace.IsInherited))
                        {
                            $obj = New-Object -TypeName PSObject -Property @{
                                    MailboxName = $item.mailnickname
                                    Owner = $ace.IdentityReference.Value
                                }
                            # Add the object to our array
                            $results += $obj
                        }
                    }
                }
            }
        }

    }
    User {
        # Get the mailbox
        $all = Get-ADUser -Filter {(mailnickname -like "*")} -Properties mailnickname,msExchMailboxSecurityDescriptor -SearchScope 2 -Server "$PDC" -ResultSetSize 10000
        $count = 0
        foreach ($item in $all)
        {
            # It's a resource consuming task so let's indicate some progress
            $count++
            Write-Progress -activity "Seaching username" -status "Percent added: " -PercentComplete (($count/$all.Count)*100)
            foreach ($ace in $item.msExchMailboxSecurityDescriptor.Access)
            {
                if ($ace.ActiveDirectoryRights -band [System.DirectoryServices.ActiveDirectoryRights]::CreateChild)
                {
                    if (-not($Ace.IsInherited))
                    {
                        if (($ace.IdentityReference.Value) -match $UserName)
                        {
                                $obj = New-Object -TypeName PSObject -Property @{
                                        MailboxName = $item.mailnickname
                                        Owner = $UserName
                                    }
                                # Add the object to our array
                                $results += $obj
                         }
                    }
                }
            }
        }
    }
}

return $results
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s