ActiveDirectory.psm1

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
#region Test-ActiveDirectoryGroupMemebership
Function Test-ActiveDirectoryGroupMembership
{
    <#
    .SYNOPSIS
 
    Test if a user is a member of a group.
    .DESCRIPTION
 
    Test if a user is member of a security group.
    .PARAMETER User
 
    The username of the user.
    .PARAMETER Group
 
    The name of the group.
    .EXAMPLE
 
    Test-ADNestedGroupMembership myuser mygroup
    #>


    Param
    (
        [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias("Username", "SamAccountName")]
        [string[]]$User,

        [Parameter(Mandatory=$True,Position=2)]
        [Alias("Groupname")]
        [string]$Group,

        [switch]$Recurse
    )

    Begin {}

    Process
    {
        # Loop through the users
        Foreach($u in $User)
        {
            # Create a custom object
            $obj = New-Object psobject
            $obj | Add-Member -MemberType NoteProperty -Name User -Value $u
            $obj | Add-Member -MemberType NoteProperty -Name Group -Value $Group

            # Test if the user exists
            try
            {
                $aduser = Get-ADUser $u -ErrorAction Stop
            }
            catch
            {
                Write-Error "Could not find user $u"
                continue
            }

            # Test if the group exists
            try
            {
                $adgroup = Get-ADGroup $Group -ErrorAction Stop
            }
            catch
            {
                Throw "Could not find group $Group"
            }

            $obj | Add-Member NoteProperty "User DN" $aduser.DistinguishedName
            $obj | Add-Member NoteProperty "Group DN" $adgroup.DistinguishedName

            if($Recurse)
            {
                # Recursive query
                if(
                    Get-ADUser `
                        -Filter "memberOf -RecursiveMatch '$($adgroup.DistinguishedName)'" `
                        -SearchBase $($aduser.DistinguishedName)
                )
                {
                    $obj | Add-Member -MemberType NoteProperty -Name Member -Value $True
                }
                else
                {
                    $obj | Add-Member -MemberType NoteProperty -Name Member -Value $false
                }
            }
            else
            {
                # Direct member query
                if(
                    Get-ADUser `
                        -Filter {memberof -eq $adGroup.DistinguishedName -and distinguishedname -eq $aduser.DistinguishedName}
                )
                {
                    $obj | Add-Member -MemberType NoteProperty -Name Member -Value $True
                }
                else
                {
                    $obj | Add-Member -MemberType NoteProperty -Name Member -Value $false
                }
            }

            $obj
        }
    }

    End {}
}
#endregion

#region Test-ActiveDirectoryIsDomainAdmin
Function Test-ActiveDirectoryIsDomainAdmin
{
    <#
    .SYNOPSIS
 
    Test if a user has domain administrator privileges.
    .DESCRIPTION
 
    Test if a user is member of the Domain Admins security group including nested groups.
    .PARAMETER Username
 
    The username of the user.
    .EXAMPLE
 
    Test-ADIsDomainAdmin myuser
    This will return true if the user is a member of the Domain Admins group or false if not.
    #>


    Param
    (
        [Parameter(
            Mandatory=$True,
            Position=0,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)
        ]
        [alias("Username")]
        [string[]]$User
    )

    Begin {}

    Process
    {
        Foreach($u in $User)
        {
            # Get the user
            try
            {
                $aduser = Get-ADUser $u -ErrorAction Stop -Properties SamAccountName
            }
            catch
            {
                Write-Error "Could not find user $u."
            }

            Test-ActiveDirectoryGroupMembership -User $aduser.SamAccountName -Group "Domain Admins" -Recurse
        }
    }

    End {}
}
#endregion

#region Get-ActiveDirectoryUserGroupMembershipHistory
Function Get-ActiveDirectoryUserGroupMembershipHistory
{
    <#
    .SYNOPSIS
 
    Get the group membership history of an account
    .DESCRIPTION
 
    Get the addition history of a user regarding security groups. This cmdlet only displays the groups that the user is member of and only the date when the user was originaly added.
    .PARAMETER Username
 
    The username of the user.
    .PARAMETER Group
 
    The name of the group
    .EXAMPLE
 
    Get-ADUserGroupMembershipHistory -Username myuser -Group mygroup
    This will return the memberhip additions of the myuser group to and from the mygroup group.
    #>


    Param
    (
        [Parameter(Mandatory=$True,Position=0)]
        [string]$Username,
        [Parameter(Mandatory=$False,Position=1)]
        [string]$Group,
        [Parameter(Mandatory = $False, Position = 2)]
        [string]$Server = $env:COMPUTERNAME
    )

    # Get the user from Active Directory

    try
    {
        $userobj  = Get-ADUser $username -ErrorAction Stop
    }
    catch
    {
        Throw "Could not find user $Username."
    }
    
    $results = 
        Get-ADUser $userobj.DistinguishedName -Server $Server -Properties memberOf |
            Select-Object -ExpandProperty memberOf |
                ForEach-Object {
                    Get-ADReplicationAttributeMetadata $_ -Server $Server -ShowAllLinkedValues | 
                        Where-Object {`
                            $_.AttributeName -eq 'member' -and 
                            $_.AttributeValue -eq $userobj.DistinguishedName} |
                            Select-Object -Property `
                                @{name="OriginallyAdded";Expression={$_.FirstOriginatingCreateTime}}, `
                                @{name="User";Expression={$username}}, `
                                @{name="Group";Expression={(Get-ADObject -Identity $_.object).Name}}, `
                                @{name="UserDN";Expression={$_.AttributeValue}}, `
                                @{name="GroupDN";Expression={$_.Object}} 
                }
    
    # Narrow down th
    if( $group )
    {
        # Get the group
        try
        {
            $adgroup = Get-AdGroup $Group -ErrorAction Stop -Server $Server
        }
        catch
        {
            Throw "Could not find group $group."
        }

        # Filter the results
        $results |
            Where-Object {$_.groupdn -eq $adgroup.distinguishedname}
    }
    else
    {
        $results
    }
}
#endregion

#region Get-ActiveDirectoryAccountLockEvent
Function Get-ActiveDirectoryAccountLockEvent
{
    <#
    .Synopsis
       Get the account lock events.
    .DESCRIPTION
       Get the account lock events from the security event log of the domain controllers.
    .EXAMPLE
        Get-ActiveDirectoryAccountLockEvent -StartTime $start
        Account Timestamp Domain Controller Caller Computer
        ------- --------- ----------------- ---------------
        cpolydorou 27/5/2017 7:44:43 μμ DC3 WINDOWS10
        cpolydorou 27/5/2017 7:44:43 μμ DC1 WINDOWS10
    #>


    [CmdletBinding()]
    Param
    (
        # The starting date
        [Parameter(Mandatory=$false, 
                   Position=0)]
        [DateTime]
        $StartTime
    )

    # Form the event log query
    $now = [DateTime]::Now

    # If the start time has not been specified, we'll search for events in last hour
    if(-Not $StartTime)
    {
        $StartTime = $now.AddHours(-1)
    }
    $timespan = $now - $StartTime

    $query = @"
        <QueryList>
            <Query Id="0" Path="Security">
                <Select Path="Security">*[System[(EventID=4740) and TimeCreated[timediff(@SystemTime) &lt;= $($timespan.TotalMilliseconds)]]]</Select>
            </Query>
        </QueryList>
"@


    # Import the ActiveDirectory module
    Write-Verbose "Getting Domain Controllers"
    try
    {
        $domainControllers = Get-ADDomainController -Filter * -ErrorAction Stop | % Name
    }
    catch
    {
        throw "Could not get the Domain Controllers."
    }

    # Get the events from all domain controllers
    Write-Verbose "Getting events"
    $events =

    # Search for the relative events on the domain controllers
    Invoke-Command -ComputerName $domainControllers `
                   -ScriptBlock {
                        Param( $q )

                        try
                        {
                            Get-WinEvent -FilterXml $q -ErrorAction Stop
                        }
                        catch
                        {
                            if($_.Exception.Message.StartsWith("No events were found"))
                            {
                                return $null
                            }
                            else
                            {
                                throw $_.Exception
                            }
                        }
                    } -ArgumentList $query

    # Process the events
    Write-Verbose "Processing events" 
    foreach($e in $events)
    {
        if($e -ne $null)
        {
            # Get the account that was locked out
            $startIndex = $e.Message.IndexOf("Account That Was Locked Out:") + 28
            $account = $e.message.substring($startIndex, $e.message.length - $startIndex)
            $startIndex = $account.IndexOf("Account Name:") + 13
            $account = $account.Substring($startIndex, $account.length - $startIndex)
            $endIndex = $account.IndexOf("`r")
            $account = $account.substring(0, $endIndex).Trim()
    
            # Get the caller computer
            $start = $e.Message.IndexOf("Caller Computer Name") + 21
            $caller = $e.message.substring($start, $e.message.length - $start).Trim()

            # Create a custom object
            $obj = New-Object psobject -Property @{
                                                    "Timestamp" = $e.TimeCreated
                                                    "Account" = $account
                                                    "Caller Computer" = $caller
                                                    "Domain Controller" = $e.PSComputerName
                                                }
            $obj
        }
    }
}
#endregion

#region Compare-ActiveDirectoryObject
Function Compare-ActiveDirectoryObject
{
    <#
    .Synopsis
       Compare two Active Directory objects.
    .DESCRIPTION
       Compare two Active Directory objects.
    .EXAMPLE
        PS C:\> $ADObject1 = Get-ADUser cpolydorou -Properties *
 
        PS C:\> $ADObject2 = Get-ADUser administrator -Properties *
 
        PS C:\> Compare-ActiveDirectoryObject -ReferenceObject $ADObject1 -DifferenceObject $ADObject2 | Select-Object -First 10
 
        PropertyName ReferenceValue DifferenceValue Status
        ------------ -------------- --------------- ------
        AccountExpirationDate Equal
        accountExpires 9223372036854775807 0 Different
        AccountLockoutTime 27/5/2017 7:44:43 μμ Different
        AccountNotDelegated False False Equal
        adminCount 1 1 Equal
        AllowReversiblePasswordEncryption False False Equal
        AuthenticationPolicy {} {} Equal
        AuthenticationPolicySilo {} {} Equal
        BadLogonCount 3 0 Different
        badPasswordTime 131403770838829365 131415008228411927 Different
     
        Get two users from Active Directory and compare all their properties (The first 10 have been selected).
    .EXAMPLE
        PS C:\> Compare-ActiveDirectoryObject -ReferenceObject $ADObject1 -DifferenceObject $ADObject2 -Properties SamAccountName,UserPrincipalName
 
        PropertyName ReferenceValue DifferenceValue Status
        ------------ -------------- --------------- ------
        SamAccountName cpolydorou Administrator Different
        UserPrincipalName cpolydorou@LAB.local Administrator@LAB.local Different
 
        Compare only the properties SamAccountName and UserPrincipalName of the objects from the previous example.
    #>


    [cmdletBinding()]

    Param(
        # The reference object
        [Parameter(Mandatory=$true, 
                   Position=0)]
        [ValidateNotNullOrEmpty()]
        [PSObject]
        $ReferenceObject,
        
        
        # The difference object
        [Parameter(Mandatory=$true, 
                   Position=1)]
        [ValidateNotNullOrEmpty()]
        [PSObject]
        $DifferenceObject,

        # The difference object
        [Parameter(Mandatory=$false, 
                   Position=2)]
        [string[]]$Properties
    )
    
    # If a list of properties has not been provided, use all the properties of the objects
    if(-not $Properties)
    {
        # Get the names of the properties of the reference object
        $Properties = $ReferenceObject | Get-Member -MemberType Property,NoteProperty | % Name

        # Get the names of the properties of the difference object
        $Properties += $DifferenceObject | Get-Member -MemberType Property,NoteProperty | % Name
    
        # Select the unique values
        $Properties = $Properties | Sort-Object | Select-Object -Unique
    }
        
    # Loop through each property
    foreach ($property in $Properties)
    {
        # Compare the property between the objects
        $diff = Compare-Object $ReferenceObject $DifferenceObject -Property $property
        if ($diff)
        {
            # There is a difference
            $props = [ordered]@{
                                "PropertyName" = $property
                                "ReferenceValue" = ($diff | ? {$_.SideIndicator -eq ‘<='} | % $($property))
                                "DifferenceValue" = ($diff | ? {$_.SideIndicator -eq ‘=>’} | % $($property))
                                "Status" = "Different"
                    }
        }
        else
        {
            # The properies are equal
            $props = [ordered]@{
                                "PropertyName" = $property
                                "ReferenceValue" = $ReferenceObject.($property)
                                "DifferenceValue" = $DifferenceObject.($property)
                                "Status" = "Equal"
                    }
        }

        # Create a custom object
        New-Object PSObject -Property $props
    }
}
#endregion

#region Get-ActiveDirectoryGroupMember
function Get-ActiveDirectoryGroupMember
{
    <#
    .Synopsis
       Get the members of an Active Directory group.
    .DESCRIPTION
       Get the members of an Active Directory group.
    .EXAMPLE
        PS C:\> Get-ActiveDirectoryGroupMember -Identity "Domain Admins" -Recurse
 
        DistinguishedName Name ObjectClass ObjectGUID
        ----------------- ---- ----------- ----------
        CN=InfrastructureAdmins,OU=SecurityGroups,DC=lab,DC=local InfrastructureAdmins group 08ee2512-4ad1-4f60-8bca-5153cddccc47
        CN=Administrator,CN=Users,DC=lab,DC=local Administrator user 32ebb121-b479-4bab-8c1c-9e96997e2834
    .EXAMPLE
        PS C:\> Get-ADGroup "Domain Admins" | Get-ActiveDirectoryGroupMember -Recurse
 
        DistinguishedName Name ObjectClass ObjectGUID
        ----------------- ---- ----------- ----------
        CN=InfrastructureAdmins,OU=SecurityGroups,DC=lab,DC=local InfrastructureAdmins group 08ee2512-4ad1-4f60-8bca-5153cddccc47
        CN=Administrator,CN=Users,DC=lab,DC=local Administrator user 32ebb121-b479-4bab-8c1c-9e96997e2834
    #>


    [CmdletBinding(PositionalBinding=$false)]

    Param
    (
        # The group
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [string]
        $Identity,

        # Recursive query
        [Parameter()]
        [switch]
        $Recurse,

        # The server
        [Parameter(Mandatory=$false, 
                   Position=1)]
        [string]
        $Server

    )

    Begin
    {
        #region Load the Active Directory module
        try
        {
            Import-Module ActiveDirectory -ErrorAction Stop
        }
        catch
        {
            Throw "Could not load the 'ActiveDirectory' module."
        }
        #endregion
    }

    Process
    {
        #region Get the group
        $group = Get-ADGroup $Identity -ErrorAction Stop
        #endregion

        # The parameters for the command
        $params = @('-ResultSetSize', '$null')

        #region Set the query type (one level - recursive)
        if($Recurse)
        {
            $params += "-Filter"
            $params += "`"(memberOf -RecursiveMatch '$($group.DistinguishedName)')`""
        }
        else
        {
            $params += "-LDAPFilter"
            $params += "`"(memberof=$($group.distinguishedname))`""
        }
        #endregion

        #region Set the server
        if($Server)
        {
            $params += "-Server"
            $params += $Server
        }
        #endregion

        #region Execute the command
        $sb = [scriptblock]::Create("Get-ADObject " + $params)
        Invoke-Command -ScriptBlock $sb
        #endregion
    }

    End
    {
    }
}
#endregion

#region Get-ActiveDirectoryEmailAddress
function Get-ActiveDirectoryEmailAddress
{
    <#
    .Synopsis
       Get the SMTP addresses using Active Directory.
    .DESCRIPTION
       Get the SMTP addresses of an Active Directory object using .NET.
    .EXAMPLE
        PS C:\> Get-ActiveDirectoryEmailAddress -SamAccountName cpolydorou
 
        DistinguishedName : CN=Christos Polydorou,CN=Users,DC=LAB,DC=LOCAL
        SamAccountName : cpolydorou
        UserPrincipalName : cpolydorou@lab.local
        SMTPAddresses : {cpolydorou@lab.local, cp@lab.local}
        PrimarySMTPAddress : cpolydorou@lab.local
 
        Get the SMTP Addresses of the user with SamAccountName "cpolydorou"
    #>


    [CmdletBinding(DefaultParameterSetName='UserPrincipalName')]

    Param
    (
        # Query using UserPrincipalName
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0,
                   ParameterSetName='UserPrincipalName')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        $UserPrincipalName,

        # Query using SamAccountname
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0,
                   ParameterSetName='SamAccountName')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        $SamAccountName,

        # Query using DistinguishedName
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0,
                   ParameterSetName='DistinguishedName')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        $DistinguishedName
    )

    Begin
    {
        # Prepare the Active Directory searcher
        $objDomain = New-Object System.DirectoryServices.DirectoryEntry
        $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
        $objSearcher.SearchRoot = $objDomain
        $objSearcher.PageSize = 1
    }
    Process
    {
        # Form the query
        if($UserPrincipalName)
        {
            $query = "((userprincipalname=$UserPrincipalName))"
        }
        if($SamAccountName)
        {
            $query = "((samaccountname=$SamAccountName))"
        }
        if($DistinguishedName)
        {
            $query = "((DistinguishedName=$DistinguishedName))"
        }

        # Get the Active Directory object
        $objSearcher.Filter = $query
        $objSearcher.SearchScope = "Subtree"
        $colProplist = "DistinguishedName", "SamAccountName", "UserPrincipalName", "ProxyAddresses"
        foreach ($i in $colPropList)
        {
            $objSearcher.PropertiesToLoad.Add($i) |
                Out-Null
        }

        $colResults = $objSearcher.FindOne()
        # TODO: Test result
        if($colResults -eq $null)
        {
            Write-Error "Could not find a user."
            return
        }

        if($colResults.Properties["proxyaddresses"] -ne $null)
        {
            $smtpAddresses = New-Object System.Collections.ArrayList

            foreach($a in $colResults.Properties["proxyaddresses"])
            {
                if($a.tolower().startswith("smtp:"))
                {
                    $smtpAddresses.Add($a.split(":")[1]) |
                        Out-Null

                    if($a.startswith("SMTP:"))
                    {
                        $primarySMTPAddress = $a.split(":")[1]
                    }
                }
            }
        }

        # Create a custom object
        $properties = [ordered]@{
                        "DistinguishedName" = $colResults.Properties["DistinguishedName"][0]
                        "SamAccountName" = $colResults.Properties["SamAccountName"][0]
                        "UserPrincipalName" = $colResults.Properties["UserPrincipalName"][0]
                        "SMTPAddresses" = $smtpAddresses
                        "PrimarySMTPAddress" = $primarySMTPAddress
                      }
        New-Object -TypeName psobject -Property $properties                                
    }
    End
    {
        # Clean up
        $objSearcher.Dispose()
    }
}
#endregion

#region Get-ActiveDirectoryGroupMembership
function Get-ActiveDirectoryGroupMembership
{
    <#
    .Synopsis
       Get the groups an Active Directory object is a member of.
    .DESCRIPTION
       Get the groups an Active Directory object is a member of having the option to include
       all the groups (including groups that are nested).
    .EXAMPLE
        PS C:\> Get-ActiveDirectoryGroupMembership -Identity "CN=Christos Polydorou,CN=Users,DC=lab,DC=local"
 
        DistinguishedName GroupCategory GroupScope Name ObjectClass ObjectGUID SamAccountName SID
        ----------------- ------------- ---------- ---- ----------- ---------- -------------- ---
        CN=Test Group 1 Nested,OU=Tes... Security Global Test Group 1 Nested group 326195ba-2d8b-40f0-8a39-1c08... Test Group 1 Nested S-1-5-21-3554682577-58629175...
 
        The user is a direct member of the group "Test Group 1 Nested" only.
    .EXAMPLE
        PS C:\> Get-ActiveDirectoryGroupMembership -Identity "CN=Christos Polydorou,CN=Users,DC=lab,DC=local" -Recurse
 
        DistinguishedName GroupCategory GroupScope Name ObjectClass ObjectGUID SamAccountName SID
        ----------------- ------------- ---------- ---- ----------- ---------- -------------- ---
        CN=Test Group 1 Parent,OU=Tes... Security Global Test Group 1 Parent group d19916ff-106a-49c4-9aa6-78fa... Test Group 1 Parent S-1-5-21-3554682577-58629175...
        CN=Test Group 1,OU=Test_OU,DC... Security Global Test Group 1 group 9c11c15f-d4e5-4afe-9f1a-06db... Test Group 1 S-1-5-21-3554682577-58629175...
        CN=Test Group 1 Nested,OU=Tes... Security Global Test Group 1 Nested group 326195ba-2d8b-40f0-8a39-1c08... Test Group 1 Nested S-1-5-21-3554682577-58629175...
 
        The user is a direct member of the group "Test Group 1 Nested" only. The "Test Group 1 Nested" is a member of "Test Group 1" which in turn is a member of "Test Group 1 Parent". Thus the user is concidered a member of all groups
    #>


    [CmdletBinding(PositionalBinding=$false)]

    Param
    (
        # The object to check it's membership
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [string]
        $Identity,

        # Recursive query
        [Parameter()]
        [switch]
        $Recurse
    )

    Begin
    {
        #region Load the Active Directory module
        try
        {
            Import-Module ActiveDirectory -ErrorAction Stop
        }
        catch
        {
            Throw "Could not load the 'ActiveDirectory' module."
        }
        #endregion

        #region __GetNestedGroups
        function __GetParentGroups
        {
            # Get the parent groups of a group
            Param
            (
                $DN
            )

            if(-Not $alreadyExaminedGroups.Contains($DN))
            {
                # Get the Active Directory group object
                $parent = Get-ADObject -LDAPFilter "(member=$DN)" `
                                       -ResultSetSize $null |
                                %{
                                    Get-ADGroup $_.Distinguishedname
                                }
                # Return the group
                $parent

                # Add the group to the list of already examined groups
                # in order to avoid infinate loops
                $alreadyExaminedGroups.Add($DN) | Out-Null

                # Process the next level
                foreach($p in $parent)
                {
                    # Process the group
                    __GetParentGroups -DN $p.DistinguishedName
                }
            }
        }
        #endregion
    }

    Process
    {
        #region Get the object
        $object = Get-ADObject -Identity $Identity `
                               -Properties MemberOf `
                               -ErrorAction Stop
        #endregion

        #region Save examined groups
        # This variable is used in order to avoid infinate loops
        # since many paths may lead to the same group
        $alreadyExaminedGroups = New-Object System.Collections.ArrayList
        #endregion

        #region Get the groups the object is member of
        $groups = $object | % MemberOf
        #endregion

        #region Get the groups
        if($Recurse)
        {
            # The variable to hold the result
            $result = New-Object System.Collections.ArrayList

            #region Get the Active Directory groups that are parents of the objects groups
            $groups |
                %{
                    __GetParentGroups -DN $_
                } |
                    %{
                        # Add each member to the list of groups
                        $result.Add($_) |
                            Out-Null
                    } 
            #endregion
            
            #region Get the Active Directory groups the object is a member of
            $groups |
                %{
                    # Add each member to the list of groups
                    $result.Add((Get-ADGroup $_)) |
                        Out-Null
                }
            #endregion

            # Return the result without duplicates
            $result |
                Select-Object -Unique
        }
        else
        {
            #region Get the Active Directory groups the object is a member of
            $groups |
                %{
                    Get-ADGroup $_
                }
            #endregion
        }
        #endregion
    }

    End
    {
    }
}
#endregion

#region Get-ActiveDirectoryComputerAccountCreator
function Get-ActiveDirectoryComputerAccountCreator
{
    #region Parameters
    [CmdletBinding(PositionalBinding=$false)]
    [Alias()]
    [OutputType([String])]

    Param
    (
        # The name of the computer
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $ComputerName,

        # The Domain Controller to use
        [string]
        $Server
    )
    #endregion

    #region Begin
    Begin
    {
        # Check if the Active Directory module is installed/loaded
        if((Get-Module | % Name) -notcontains "ActiveDirectory")
        {
            Write-Verbose "Importing the 'ActiveDirectory' module."

            try
            {
                Import-Module -Name "ActiveDirectory" -ErrorAction Stop -Verbose:$false
            }
            catch
            {
                Throw ("Failed to load the 'Active Directory' module. " + $_.Exception.Message)                 
            }
        }
    }
    #endregion

    #region Process
    Process
    {
        foreach($c in $ComputerName)
        {
            # Get the computer object
            Write-Verbose "Searching for a computer object named ""$c""..."
            try
            {
                if($Server)
                {
                    $computerObject = Get-ADComputer -Filter {Name -eq $c} -Properties "mS-DS-CreatorSID" -Server $Server -ErrorAction Stop
                }
                else
                {
                    $computerObject = Get-ADComputer -Filter {Name -eq $c} -Properties "mS-DS-CreatorSID" -ErrorAction Stop
                }
            }
            catch
            {
                Write-Error ("Failed to get a computer object for " + $c + " ." + $_.Exception.Message)
                continue
            }
            if($computerObject -eq $null)
            {
                Write-Error ("Failed to find a computer object with name '" + $c + "'.")
                continue
            }
            else
            {
                Write-Verbose ("Found object """ + $computerObject.DistinguishedName + """ .")
            }

            # Get the object that created the account
            Write-Verbose "Examining computer object for the creator information..."
            if([System.String]::IsNullOrEmpty($computerObject.'mS-DS-CreatorSID'))
            {
                Write-Warning "Failed to find the creator information on the computer object. The account could have been created by an administrator."
                continue
            }
            try
            {
                Write-Verbose "Searching for the object that created the computer account..."
                if($Server)
                {
                    $creator = Get-ADObject -LDAPFilter ( "(objectSID=" + $computerObject.'mS-DS-CreatorSID' + ")") -Server $Server -ErrorAction Stop
                }
                else
                {
                    $creator = Get-ADObject -LDAPFilter ( "(objectSID=" + $computerObject.'mS-DS-CreatorSID' + ")") -ErrorAction Stop
                }
            }
            catch
            {
                Write-Error ("Failed to get the object that created the computer object " + $c)
            }

            # Check if the object exists or not
            if($creator -eq $null)
            {
                Write-Warning ("Failed to find the object " + $computerObject.'mS-DS-CreatorSID' + ". The object may have been removed.")
                continue
            }
            else
            {
                # Create a custom object
                $props = [ordered]@{
                            Computer = $c
                            ComputerDistinguishedName = $computerObject.DistinguishedName
                            Creator = $creator.Name
                            CreatorDistinguishedName = $creator.DistinguishedName
                            CreatorClass = $creator.ObjectClass
                         }
                New-Object -TypeName PSObject `
                           -Property $props
            }
        }
    }
    #endregion

    #region End
    End
    {
    }
    #endregion
}
#endregion

#region Exports
Export-ModuleMember -Function Test-ActiveDirectoryGroupMembership
Export-ModuleMember -Function Test-ActiveDirectoryIsDomainAdmin
Export-ModuleMember -Function Get-ActiveDirectoryUserGroupMembershipHistory
Export-ModuleMember -Function Get-ActiveDirectoryAccountLockEvent
Export-ModuleMember -Function Compare-ActiveDirectoryObject
Export-ModuleMember -Function Get-ActiveDirectoryGroupMember
Export-ModuleMember -Function Get-ActiveDirectoryEmailAddress
Export-ModuleMember -Function Get-ActiveDirectoryGroupMembership
Export-ModuleMember -Function Get-ActiveDirectoryComputerAccountCreator
#endregion