SimpleADAdmin.psm1

Class SAGroup
{
    [string]   $Name
    [string]   $SamAccountName
    [string]   $Description
    [string]   $Info
    [string]   $Email
    [string]   $DistinguishedName
    [guid]     $ObjectGUID
    [string]   $ObjectSID
    [string[]] $MemberOf
    [string[]] $Members
    [string]   $ManagedBy
    [string]   $GroupCategory
    [string]   $GroupScope
    [datetime] $WhenCreated
    
    SAGroup ()
    {
        Write-Error "You must specify the SamAccountName of the group you want to look at" -ErrorAction Stop
    }

    SAGroup ( [string]$Identity )
    {
        $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$Identity))"
        $Found = @($Searcher.FindOne())

        If ($null -eq $Found.properties.samaccountname)
        {
            Write-Error "Unable to find ""$Identity""" -ErrorAction Stop
        }
        $this.SamAccountName       = $Found.properties.samaccountname | Select-Object -First 1

        $this.EnumerateFields()

        $this | Add-Member -MemberType ScriptProperty -Name LastModified -Value {
            $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$($this.SamAccountName)))"
            $Found = $Searcher.FindOne()

            # Enumerate LastModified
            Write-Output $Found.properties.whenchanged | Select-Object -First 1

            $this.EnumerateFields()
        }

        # Using default display properties to order the list properly
        $DefaultDisplayProperties = @(
            "Name"
            "SamAccountName"
            "Description"
            "Info"
            "Email"
            "DistinguishedName"
            "ObjectGUID"
            "ObjectSID"
            "MemberOf"
            "Members"
            "ManagedBy"
            "GroupCategory"
            "GroupScope"
            "WhenCreated"
            "LastModified"
        )
        $this | Add-Member -Force -MemberType MemberSet PSStandardMembers ([System.Management.Automation.PSMemberInfo[]]@(New-Object System.Management.Automation.PSPropertySet("DefaultDisplayPropertySet",[String[]]$DefaultDisplayProperties)))

    }

    hidden [void] EnumerateFields()
    {
        $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$($this.SamAccountName)))"
        $Found = @($Searcher.FindOne())

        #Thanks Richard Siddaway for breaking this out
        $GroupTypes = @{
            2           = [PSCustomObject]@{Category="Distribution";Scope="Global"}
            4           = [PSCustomObject]@{Category="Distribution";Scope="DomainLocal"}
            8           = [PSCustomObject]@{Category="Distribution";Scope="Universal"}
            -2147483646 = [PSCustomObject]@{Category="Security";Scope="Global"}
            -2147483644 = [PSCustomObject]@{Category="Security";Scope="DomainLocal"}
            -2147483643 = [PSCustomObject]@{Category="Security";Scope="BuiltinLocal"}
            -2147483640 = [PSCustomObject]@{Category="Security";Scope="Universal"}
        }
        
        $this.Name                 = $Found.properties.name | Select-Object -First 1
        $this.Description          = $Found.properties.description | Select-Object -First 1
        $this.Info                 = $Found.properties.info | Select-Object -First 1
        $this.Email                = $Found.properties.mail | Select-Object -First 1
        $this.DistinguishedName    = $Found.properties.distinguishedname | Select-Object -First 1
        $this.ObjectGUID           = New-Object GUID(,($Found.properties.objectguid | Select-Object -First 1))
        $this.ObjectSID            = (New-Object System.Security.Principal.SecurityIdentifier(($Found.properties.objectsid | Select-Object -First 1),0)).Value
        $this.MemberOf             = $Found.properties.memberof
        $this.Members              = $Found.properties.member
        $this.ManagedBy            = $Found.properties.managedby | Select-Object -First 1
        $this.GroupCategory        = $GroupTypes[($Found.properties.grouptype | Select-Object -First 1)].Category
        $this.GroupScope           = $GroupTypes[($Found.properties.grouptype | Select-Object -First 1)].Scope
        $this.WhenCreated          = $Found.properties.whencreated | Select-Object -First 1
    }

    hidden [PSCustomObject[]] GetMemberObject([string]$dn, [boolean]$Recurse)
    {
        $Results = New-Object -TypeName System.Collections.ArrayList
        $Searcher = [ADSISearcher]"((distinguishedName=$dn))"
        $Found = @($Searcher.FindOne())
        If ($Found.Count -eq 0)
        {
            Write-Warning "Unable to find ""$dn"""
        }
        Else
        {
            If (($Found.properties.objectclass | Select-Object -Last 1) -eq "group" -and $Recurse)
            {
                $subResults = $this.GetMembersFromGroup($dn)
                ForEach ($Result in $subResults)
                {
                    $null = $Results.Add($Result)
                }
            }
            Else
            {
                $null = $Results.Add([PSCustomObject]@{
                    Member         = $Found.properties.name | Select-Object -First 1
                    SamAccountName = $Found.properties.samaccountname | Select-Object -First 1
                    ObjectClass    = $Found.properties.objectclass | Select-Object -Last 1
                })
            }
        }
        Return $Results
    }

    hidden [PSCustomObject[]] GetMembersFromGroup ([string]$dn)
    {
        $Results = $null
        $Searcher = [ADSISearcher]"((distinguishedName=$dn))"
        $Found = @($Searcher.FindOne())
        If ($Found.Count -eq 0)
        {
            Write-Warning "Unable to find ""$dn"""
        }
        Else
        {
            $Results = ForEach ($Member in ($Found.properties.member))
            {
                $this.GetMemberObject($Member, $true)
            }
        }

        Return $Results
    }

    hidden [PSCustomObject] ValidateUserName ([string]$Identity)
    {
        $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$Identity))"
        $Found = $Searcher.FindOne()

        If ($null -eq $Found.properties.samaccountname)
        {
            Write-Error "User name ""$Identity"" was not found" -ErrorAction Stop
        }
        $Result = [PSCustomObject]@{
            Name = $Found.Properties.name
            DN   = $Found.properties.distinguishedname
        }
        Return $Result
    }

    [PSCustomObject[]] GetMembers()
    {
        $Results = ForEach ($Member in $this.Members)
        {
            $this.GetMemberObject($Member, $false)
        }
        Return $Results
    }

    [PSCustomObject[]] GetMembersRecursive()
    {
        $Results = ForEach ($Member in $this.Members)
        {
            $this.GetMemberObject($Member, $true)
        }
        Return $Results
    }

    [void] AddMember ([string]$Identity)
    {
        $User = $this.ValidateUserName($Identity)

        $GroupObj = [ADSI]"LDAP://$($this.DistinguishedName)"
        $GroupObj.Add("LDAP://$($User.DN)")
        Write-Verbose "Added ""$($User.Name)"" to Group ""$($this.Name)"" which will take a few minutes to show up in `$SAGroup" -Verbose
    }

    [void] RemoveMember ([string]$Identity)
    {
        $User = $this.ValidateUserName($Identity)

        $GroupObj = [ADSI]"LDAP://$($this.DistinguishedName)"
        $GroupObj.Remove("LDAP://$($User.DN)")
        Write-Verbose "Removed ""$($User.Name)"" from group ""$($this.Name)""" -Verbose
    }
}

Class SAUser
{
    [string]   $Name
    [string]   $SamAccountName
    [string]   $Title
    [string]   $Description
    [string]   $GivenName
    [string]   $Surname
    [string]   $Email
    [boolean]  $PasswordNeverExpires
    [boolean]  $PasswordNotRequired
    [string]   $DistinguishedName
    [string]   $UserPrincipalName
    [guid]     $ObjectGUID
    [string]   $ObjectSID
    [string[]] $MemberOf
    [string]   $Manager
    [string]   $LastLogon = "Unknown"
    [boolean]  $LockedOut
    [int]      $BadPasswordCount
    [boolean]  $PasswordExpired
    [datetime] $PasswordLastSet

    SAUser ()
    {
        Write-Error "You must provide a username" -ErrorAction Stop
    }

    SAUser ( [string]$Identity )
    {
        $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$Identity))"
        $Found = $Searcher.FindOne()

        If ($null -eq $Found.properties.samaccountname)
        {
            Write-Error "Unable to locate user name ""$Identity""" -ErrorAction Stop
        }

        # Fill in the object
        $this.SamAccountName = $Found.properties.samaccountname
        $this.EnumerateFields()

        # Add Enabled field, and field refresh
        $this | Add-Member -MemberType ScriptProperty -Name Enabled -Value {
            $ACCOUNTDISABLE            = 0x000002

            $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$($this.SamAccountName)))"
            $Found = $Searcher.FindOne()

            Write-Output (-not [bool]($Found.userAccountControl -band $ACCOUNTDISABLE))
            $this.EnumerateFields()
        }

        # Set Default property view
        $DefaultDisplayProperties = @(
            "Name"
            "SamAccountName"
            "Title"
            "Enabled"
            "LockedOut"
            "BadPasswordCount"
            "LastLogon"
        )
        $this | Add-Member -Force -MemberType MemberSet PSStandardMembers ([System.Management.Automation.PSMemberInfo[]]@(New-Object System.Management.Automation.PSPropertySet("DefaultDisplayPropertySet",[String[]]$DefaultDisplayProperties)))
    }

    hidden [void] EnumerateFields ()
    {
        $DONT_EXPIRE_PASSWORD      = 0x010000
        $PASSWORD_EXPIRED          = 0x800000
        $ADS_UF_PASSWD_NOTREQD     = 0x0020

        $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$($this.SamAccountName)))"
        $Found = $Searcher.FindOne()

        $this.Name                 = $Found.properties.displayname | Select-Object -First 1
        $this.SamAccountName       = $Found.properties.samaccountname | Select-Object -First 1
        $this.Title                = $Found.properties.title | Select-Object -First 1
        $this.Description          = $Found.properties.description | Select-Object -First 1
        $this.GivenName            = $Found.properties.givenname | Select-Object -First 1
        $this.Surname              = $Found.properties.sn | Select-Object -First 1
        $this.Email                = $Found.properties.mail | Select-Object -First 1
        $this.PasswordNeverExpires = [bool]($Found.userAccountControl -band $DONT_EXPIRE_PASSWORD)
        $this.PasswordNotRequired  = [bool]($Found.userAccountControl -band $ADS_UF_PASSWD_NOTREQD)
        $this.DistinguishedName    = $Found.properties.distinguishedname | Select-Object -First 1
        $this.UserPrincipalName    = $Found.properties.userprincipalname | Select-Object -First 1
        $this.ObjectGUID           = New-Object GUID(,($Found.properties.objectguid | Select-Object -First 1))
        $this.ObjectSID            = (New-Object System.Security.Principal.SecurityIdentifier(($Found.properties.objectsid | Select-Object -First 1),0)).Value
        $this.MemberOf             = $Found.properties.memberof
        $this.Manager              = $Found.properties.manager | Select-Object -First 1
        $this.LockedOut            = (($Found.properties.lockouttime | Select-Object -First 1) -gt 0)
        $this.BadPasswordCount     = $Found.properties.badpwdcount | Select-Object -First 1
        $this.PasswordExpired      = [bool]($Found.userAccountControl -band $PASSWORD_EXPIRED)
        $this.PasswordLastSet      = [DateTime]::FromFileTime(($Found.properties.pwdlastset | Select-Object -First 1))
    }

    hidden [PSCustomObject] GetGroupNames ()
    {
        $Results = ForEach ($Member in $this.MemberOf)
        {
            $Searcher = [ADSISearcher]"(distinguishedName=$Member)"
            $Found = $Searcher.FindOne()
            [PSCustomObject]@{
                Name              = $Found.properties.name | Select-Object -First 1
                SamAccountName    = $Found.properties.samaccountname | Select-Object -First 1
                distinguishedName = $Found.properties.distinguishedname | Select-Object -First 1
            }
        }
        Return $Results
    }

    hidden [void] AddUserToGroup ( [string]$DN )
    {
        $Searcher = [ADSISearcher]"(distinguishedName=$DN)"
        $Found = $Searcher.FindOne()

        If ($this.MemberOf -contains $DN)
        {
            Write-Error "User is already a member of group ""$($Found.properties.name)""" -ErrorAction Stop
        }
        Else
        {
            $GroupObj = [ADSI]"LDAP://$($Found.properties.distinguishedname)"
            $GroupObj.Add("LDAP://$($this.distinguishedName)")
            Write-Verbose "Added to Group ""$($Found.properties.name)"", will take a minute to show up in `$SAUser" -Verbose
        }
    }

    hidden [PSCustomObject] Get4740Events ( [datetime]$Start, [datetime]$End )
    {
        $PDCEmulator = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers | Where-Object Roles -Contains "PdcRole" | Select-Object -ExpandProperty Name
        Write-Verbose "PDC Emulator: $PDCEmulator" -Verbose

        $FilterHash = @{
            LogName   = "Security"
            StartTime = $Start
            EndTime   = $End
            ID        = 4740
        }

        $Results = $null
        Write-Verbose "Searching (be patient)..." -Verbose
        Try {
            $Results = Get-WinEvent -ComputerName $PDCEmulator -FilterHashtable $FilterHash -ErrorAction Stop | 
                Where-Object Message -Like "*$($this.SamAccountName)*" | 
                Select-Object TimeCreated,
                    @{Name="User";Expression={$Username}},
                    @{Name="LockedOn";Expression={$PSItem.Properties.Value[1]}},
                    @{Name="DC";Expression={$PDCEmulator}}
        }
        Catch {
            Write-Error "Unable to retrieve event log for $PDCEmulator because ""$_""" -ErrorAction Stop
        }
        Return $Results
    }

    [void] Unlock ()
    {
        $Found = [ADSI]"LDAP://$($this.DistinguishedName)"
        $Found.Put("lockouttime",0)
        $Found.SetInfo()
    }

    [PSCustomObject[]] GetGroups ()
    {
        $Groups = $this.GetGroupNames() | Sort-Object
        Return $Groups
    }

    [PSCustomObject[]] GetGroups ( [string]$Filter )
    {
        $Groups = $this.GetGroupNames() | Where-Object Name -match $Filter | Sort-Object
        Return $Groups
    }

    [void] RemoveGroup ( [string]$GroupName )
    {
        $Searcher = [ADSISearcher]"(&(objectCategory=group)(samAccountName=$GroupName))"
        $Found = $Searcher.FindOne()

        If ($null -eq $Found.properties.samaccountname)
        {
            Write-Error "Unable to locate group ""$GroupName""" -ErrorAction Stop
        }
        Else
        {
            If ($this.MemberOf -contains $Found.properties.distinguishedname)
            {
                $GroupObj = [ADSI]"LDAP://$($Found.properties.distinguishedname)"
                $GroupObj.Remove("LDAP://$($this.DistinguishedName)")
                Write-Verbose "Removed from group ""$($Found.properties.name)""" -Verbose
            }
            Else
            {
                Write-Error "User is not currently a member of ""$GroupName""" -ErrorAction Stop
            }
        }
    }

    [void] AddGroup ( [string]$GroupName )
    {
        $Searcher = [ADSISearcher]"(&(objectCategory=group)(objectClass=group)(samAccountName=*$GroupName*))"
        $Searcher.PageSize = 1000
        $Found = $Searcher.FindAll()

        If (@($Found).Count -gt 1)
        {
            $Selected = $Found | 
                Select-Object @{Name="SamAccountName";Expression={ $_.properties.samaccountname }},
                    @{Name="DisplayName";Expression={ $_.properties.displayname }},
                    @{Name="DistinguishedName";Expression={ $_.properties.distinguishedname }} | 
                Out-GridView -Title "Select the groups to add" -OutputMode Multiple
            If (@($Selected).Count -ge 1)
            {
                $Found = ForEach ($Group in $Selected)
                {
                    $this.AddUserToGroup($Group.DistinguishedName)
                }
            }
            Else
            {
                Write-Warning "No group selected"
                Return
            }
        }
        ElseIf (@($Found).Count -eq 0)
        {
            Write-Warning "No group matching ""*$GroupName*"" found"
            Return
        }
        Else
        {
            $this.AddUserToGroup($Found.properties.distinguishedname)
        }
    }

    [void] ResetPassword ()
    {
        $Password1 = Get-Credential -UserName $this.SamAccountName -Message "Enter new password"
        $Password2 = Get-Credential -UserName $this.SamAccountName -Message "Verify new password"
        If ($Password1.GetNetworkCredential().Password -ceq $Password2.GetNetworkCredential().Password)
        {
            $UserObj = [ADSI]"LDAP://$($this.distinguishedName)"
            $UserObj.SetPassword($Password1.GetNetworkCredential().Password)
        }
        Else
        {
            Write-Error "Passwords did not match" -ErrorAction Stop
        }
    }

    [void] GetLastLogon ()
    {
        $DCs = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers | Select-Object -ExpandProperty Name
        $Count = 1
        $DCData = ForEach ($DC in $DCs)
        {
            Write-Progress -Activity "Retrieving user data from Domain Controllers" -Status "...$DC ($Count of $($DCs.Count))" -Id 0 -PercentComplete ($Count * 100 / $DCs.Count)
            $UserObj = [ADSI]"LDAP://$DC/$($this.distinguishedName)"
            If ($null -ne ($UserObj.lastlogon | Select-Object -First 1))
            {
                [datetime]::FromFileTime($UserObj.ConvertLargeIntegerToInt64(($UserObj.lastLogon | Select-Object -First 1)))
            }
            $Count ++
        }
        Write-Progress -Activity " " -Status " " -Completed
        $this.LastLogon = ($DCData | Sort-Object -Descending | Select-Object -First 1).ToString()
        
        Write-Verbose "Last Logon for $($this.Name) was $($this.LastLogon)" -Verbose
    }

    [PSCustomObject] FindLockout ()
    {
        $Start = (Get-Date).AddDays(-2)
        $End   = Get-Date
        $Results = $this.Get4740Events($Start, $End)
        Return $Results
    }




}
Function Get-SAGroup {
    <#
    .SYNOPSIS
        Simple function that will allow you to do the most common group administrative tasks from a single place.
    .DESCRIPTION
        This is a more advanced version of Get-ADGroup. It allows you to see administratively useful fields in the default view, but
        also saves the user object in a global variable:

        $SAGroup

        The advantage of this is if you want to do something to the object it's now persistent in your session. All properties on
        $SAGroup are dynamic, meaning they will update from Active Directory every time you display the variable, which means you don't
        have to keep rerunning Get-SAGroup after you've made a change in order to see it.
        
        Thee are several methods available on $SAUser for an administrator to use, they are:

        GetMembers
                  Usage: $SAUser.GetMembers()
            Description: Shows every user and group who is a member of the group.
               Overload: None

        GetMembersRecursive
                  Usage: $SAUser.GetMembersRecursive()
            Description: Shows every user who is a member of the group, even if they are part of a group that's assigned to this one.
               Overload: None

        AddMember
                  Usage: $SAUser.AddMember(SamAccountName)
            Description: Add the designated user to the group
               Overload: SamAccountName for the user you want to add

        RemoveMember
                  Usage: $SAUser.RemoveMember(SamAccountName)
            Description: Remove the designated user to the group
               Overload: SamAccountName for the user you want to remove

    .PARAMETER Identity
        Name of the group you want to interact with. If the group cannot be found, it will attempt to look for groups with a like
        name and give you the option of selecting one of those.
    .EXAMPLE
        Get-SAGroup "Test-Group"

        Name : Test Group
        SamAccountName : Test-Group
        Description : Distribution list for internal tests only
        Info :
        Email : test-group@gmail.com
        DistinguishedName : CN=test-group,OU=Internal,OU=Distribution Lists,DC=surlyadmin,DC=com
        ObjectGUID : d2fe1397-40bb-48c6-8bf7-5f5c80e127b1
        ObjectSID : S-1-5-21-1991516528-409794927-3010460085-114238
        MemberOf :
        Members : {CN=surlyadmins,OU=Internal,OU=Distribution Lists,DC=surlyadmin,DC=com}
        ManagedBy : CN=Martin Pugh,OU=Employees,DC=surlyadmin,DC=com
        GroupCategory : Distribution
        GroupScope : Universal
        WhenCreated : 2/7/2018 1:46:52 PM
        LastModified : 9/6/2018 6:04:46 PM

    .NOTES
        Author: Martin Pugh
        Twitter: @thesurlyadm1n
        Spiceworks: Martin9700
        Blog: www.thesurlyadmin.com
      
        Changelog:
            05/25/19 Initial Release
    .LINK
    
    #>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true,
            Position = 0)]
        [Alias("Group","SamAccountName","Name")]
        [string]$Identity
    )

    # Clear old variable (if present)
    Remove-Variable -Name SAGroup -Scope Global -ErrorAction SilentlyContinue

    # Find the group
    $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$Identity))"
    $Found = @($Searcher.FindAll())
    If ($Found.Count -ne 1)
    {
        If ($Found.Count -eq 0)
        {
            Write-Verbose "No user matching ""$Identity"", trying for a match"
            $Searcher = [ADSISearcher]"(&(objectClass=group)(name=*$Identity*))"
            $Found = @($Searcher.FindAll())
        }
        If ($Found.Count -gt 1)
        {
            # Found more than one, need to select which one you want
            $Selected = $Found | 
                Select-Object @{Name="SamAccountName";Expression={ $_.properties.samaccountname }},
                    @{Name="DisplayName";Expression={ $_.properties.displayname }},
                    @{Name="Description";Expression={ $_.properties.description }} | 
                Sort-Object -Property SamAccountName |
                Out-GridView -Title "Select the correct group" -PassThru
            If (@($Selected).Count -eq 0)
            {
                Write-Warning "No group selected"
                Return
            }
            $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$($Selected.SamAccountName)))"
            $Found = $Searcher.FindOne()
        }
        ElseIf ($Found.Count -eq 0)
        {
            Write-Error "Unable to locate group matching *$Identity*" -ErrorAction Stop
        }
    }

    # Set global variable and return object
    $Global:SAGroup = [SAGroup]::New($Found.properties.samaccountname)
    Return $Global:SAGroup
}

Function Get-SAUser {
    <#
    .SYNOPSIS
        Simple function that will allow you to do the most common user administrative tasks from a single place.
    .DESCRIPTION
        This is a more advanced version of Get-ADUser. It allows you to see administratively useful fields in the default view, but
        also saves the user object in a global variable:

        $SAUser

        The advantage of this is if you want to do something to the object it's now persistent in your session. All properties on
        $SAUser are dynamic, meaning they will update from Active Directory every time you display the variable.

        This means you don't have to keep rerunning Get-SAUser after you've made a change in order to see it.
        
        Thee are several methods available on $SAUser for an administrator to use, they are:

        AddGroup
                  Usage: $SAUser.AddGroup("NameOfGroup")
            Description: Add the user to a group.
               Overload: You can add the name of a group in the overload and the function will find all groups that match that name
                         pattern and let you select which group or groups you want to add. If you give an exact match it will just
                         add it without prompting.

        FindLockout
                  Usage: $SAUser.FindLockedout()
            Description: Will go to the PDC emulator and look for event ID 4740 (lockout) in the Security Event Log.
               Overload: None

        GetGroups
                  Usage: $SAUser.GetGroups()
            Description: The "MemberOf" field will always show what groups the user is in, but it's the FQDN. Use the GetGroups()
                         method to see just their Name.
               Overload: You can add an overload to filter the result: $SAUser.GetGroups("test")

        GetLastLogon
                  Usage: $SAUser.GetLastLogon()
            Description: Will go out to all domain controllers in your domain and locate the latest logon for the user.
               Overload: None

        RemoveGroup
                  Usage: $SAUser.RemoveGroup("NameOfGroup")
            Description: Remove the user from the specified group.
               Overload: Name of the group, or closest match. If you specify the exact name, or the filter data you provide only has one
                         match thenthe user will be removed from the group without prompt. If there are more then one match you will be
                         asked to select the group or groups you want to remove.

        ResetPassword
                  Usage: $SAUser.ResetPassword()
            Description: Method will then prompt for new password
               Overload: None

        Unlock
                  Usage: $SAUser.Unlock()
            Description: Will unlock the user account
               Overload: None

    .PARAMETER User
        Full SamAccountName, or partial name of the user. If partial all users that match will be shown in a window and you can select the
        one you want

    .INPUTS
        None
    .OUTPUTS
        $SAUser PSCustomObject
    .EXAMPLE
        Get-SAUser mpugh
        $SAUser.Unlock()

        Get user information for mpugh, see that the account is locked. Use the Unlock() method to unlock the account.

    .EXAMPLE
        Get-SAUser Martin

        Shows a large list of users. Select Martin Pugh
    .NOTES
        Author: Martin Pugh
        Date: 8/11/2016
      
        Changelog:
            08/11/16 MLP - MVP (minimum viable product) release with Readme.md and updated help
            05/26/19 MLP - Converted to using class
    .LINK
        https://github.com/martin9700/SimpleADAdmin
    #>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [Alias("User","UserName","SamAccountName","Name")]
        [string]$Identity
    )

    $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$Identity))"
    $Found = $Searcher.FindOne()
    If ($Found.Count -eq 0)
    {
        Write-Verbose "No user matching $SAUser, trying for a match"
        $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(displayName=*$Identity*))"
        $Found = $Searcher.FindAll()
        If (@($Found).Count -gt 1)
        {
            #Found more than one, need to select which one you want
            $Selected = $Found | 
                Select-Object @{Name="SamAccountName";Expression={ $_.properties.samaccountname }},
                    @{Name="DisplayName";Expression={ $_.properties.displayname }} | 
                Out-GridView -Title "Select the user you want" -PassThru
            If (@($Selected).Count -eq 0)
            {
                Write-Warning "No user selected"
                Return
            }
            $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$($Selected.SamAccountName)))"
            $Found = $Searcher.FindOne()
        }
        If (@($Found).Count -eq 0)
        {
            Write-Error "No user found, exiting" -ErrorAction Stop
        }
    }

    #Create the object
    $Global:SAUser = [SAUser]::New($Found.properties.samaccountname)

    #Display it
    $Global:SAUser
}