Test-ADUser.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function Test-ADUser {
    [CmdletBinding()]
    param (
        [alias('UserName')]
        [Parameter(Mandatory=$false,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string[]]$Identity = $env:USERNAME
        )

    begin {
        Write-Verbose -Message 'Gathering a list of expired user accounts.'
        $ExpiredUsers = Search-ADAccount -AccountExpired -UsersOnly -ResultSetSize $null
        }
    process {
    
        foreach ($Id in $Identity) {
            try {
                Write-Verbose -Message "Querying for user $Id"
                $User = Get-ADUser -Identity $Id -ErrorAction Stop
                $UserProperties = [ordered]@{
                    Username = $User.samaccountname
                    Exists = $true
                    Enabled = $User.Enabled
                    Expired = $ExpiredUsers.samaccountname -contains $User.samaccountname
                    }
                $UserObject = New-Object -TypeName PSCustomObject -Property $UserProperties
                }
            catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                Write-Warning "$Id does not exist in Active Directory"
                $UserProperties = [ordered]@{
                    Username = $Id
                    Exists = $false
                    Enabled = $null
                    Expired = $null
                    }
                $UserObject = New-Object -TypeName PSCustomObject -Property $UserProperties

                }
            catch {
                Write-Error "Some other error $Error[0].Exception.Message"
                }

            $UserObject        
        
            }
    
        }
    end {}
}