Audit/Audit.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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
<#
.Synopsis
   Enumerates Logged On Sessions on a give host.
.DESCRIPTION
   Enumerates Logged On Sessions on a give host using WMI.
.EXAMPLE
   Get-AuditLogedOnSessions | where {$_.processes.count -gt 0}

   Retrieves sessions that have running processes.

#>

function Get-AuditLogedOnSessions 
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$false)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter(Mandatory=$false)]
        [string]$ComputerName = "localhost"
    )
    begin 
    {
        $loggedsessions = @()
        $SessionType = @{
            2  = 'Interactive'
            3  = 'Network'
            4  = 'Batch'
            5  = 'Servie'
            6  = 'Proxy'
            7  = 'Unlock'
            8  = 'NetworkCleartext'
            9  = 'NewCredentials'
            10 = 'Terminal'
            11 = 'CachedInteractive'
            12 = 'CachedTerminal'
            13 = 'CachedUnlock'
        }
    }
    process 
    {
        $sessions = Get-WmiObject win32_logonsession -Credential $Credential -ComputerName $ComputerName | select -Unique

        foreach ($session in $sessions) 
        {
            try{
                $account = $session.getrelated('win32_useraccount')
                if ($account -ne $null)
                {
                   $loggedsessions += [pscustomobject][ordered]@{Name=$account.Caption
                        SID=$account.SID
                        FullName=$account.fullname
                        Created=[System.Management.ManagementDateTimeConverter]::todatetime($session.StartTime)
                        AuthenticationType=$session.AuthenticationPackage
                        LogonType=$SessionType[[int]$session.LogonType]
                        Processes=$session.GetRelated('win32_process')
                   }
                }
            }
            catch {}
        }
    }

    end {$loggedsessions}
} 


<#
.Synopsis
   Gets a list of Domain Computer accounts and their details using ADSI.
.DESCRIPTION
   Gets a list of Domain coputer accounts and their details using ADSI. If the machine it is ran from is
   in the domain and no Domain Controller is specified it will run with the privelages of the user.
   Support the use of alternate user credentials when ran against a domain controller. The host must use
   the same DNS server to be able to reseolve the hostnames to the proper IPAddress.
.EXAMPLE
  
Get-AuditDSComputerAccount -DomainController 192.168.10.10 -Credential (Get-Credential)
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:


HostName : DC01.acmelabs.com
OperatingSystem : Windows Server 2012 Standard
ServicePack :
Version : 6.2 (9200)
DN : CN=DC01,OU=Domain Controllers,DC=acmelabs,DC=com
Created : 1/12/2013 2:08:47 AM
LastModified : 9/4/2013 7:07:02 PM
IPAddress : {192.168.10.10}

HostName : DC02.acmelabs.com
OperatingSystem : Windows Server 2008 R2 Enterprise
ServicePack : Service Pack 1
Version : 6.1 (7601)
DN : CN=DC02,OU=Domain Controllers,DC=acmelabs,DC=com
Created : 1/12/2013 2:15:02 AM
LastModified : 8/27/2013 9:29:39 AM
IPAddress : {192.168.10.12}

HostName : WIN701.acmelabs.com
OperatingSystem : Windows 7 Enterprise
ServicePack : Service Pack 1
Version : 6.1 (7601)
DN : CN=WIN701,OU=HR,DC=acmelabs,DC=com
Created : 1/12/2013 2:45:21 AM
LastModified : 8/26/2013 6:45:50 PM
IPAddress : {192.168.10.20}

HostName : WIN702.acmelabs.com
OperatingSystem : Windows 7 Ultimate
ServicePack : Service Pack 1
Version : 6.1 (7601)
DN : CN=WIN702,OU=HR,DC=acmelabs,DC=com
Created : 1/13/2013 3:27:10 PM
LastModified : 8/26/2013 6:42:00 PM
IPAddress : {192.168.10.21}

HostName : WIN801.acmelabs.com
OperatingSystem : Windows 8 Enterprise
ServicePack :
Version : 6.2 (9200)
DN : CN=WIN801,CN=Computers,DC=acmelabs,DC=com
Created : 1/13/2013 5:48:57 PM
LastModified : 9/5/2013 5:09:25 AM
IPAddress : {192.168.10.40}

HostName : WIN2K01.acmelabs.com
OperatingSystem : Windows Server 2012 Standard
ServicePack :
Version : 6.2 (9200)
DN : CN=WIN2K01,CN=Computers,DC=acmelabs,DC=com
Created : 1/14/2013 4:31:58 PM
LastModified : 8/25/2013 5:28:07 PM
IPAddress : {192.168.10.2}

HostName : win2k301.acmelabs.com
OperatingSystem : Windows Server 2003
ServicePack : Service Pack 2
Version : 5.2 (3790)
DN : CN=WIN2K301,CN=Computers,DC=acmelabs,DC=com
Created : 1/18/2013 12:51:59 PM
LastModified : 8/15/2013 8:39:43 PM
IPAddress : {192.168.10.50}
#>

function Get-AuditDSComputerAccount
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false,
        HelpMessage="Credentials to use when connecting to a Domain Controller.")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [Parameter(Mandatory=$false,
        HelpMessage="Domain controller for Domain and Site that you want to query against.")]
        [string]$DomainController,

        [Parameter(Mandatory=$false,
        HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
        [int]$Limit = 1000,

        [Parameter(Mandatory=$false,
        HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
        [ValidateSet("Subtree","OneLevel","Base")]
        [string]$SearchScope = "Subtree",

        [Parameter(Mandatory=$false,
        HelpMessage="Distinguished Name Path to limit search to.")]

        [string]$SearchDN
    )
    Begin
    {
        if ($DomainController -and $Credential.GetNetworkCredential().Password)
        {
            $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
        else
        {
            $objDomain = [ADSI]""  
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
    }

    Process
    {
        $CompFilter = "(&(objectCategory=Computer))"
        $ObjSearcher.PageSize = $Limit
        $ObjSearcher.Filter = $CompFilter
        $ObjSearcher.SearchScope = "Subtree"

        if ($SearchDN)
        {
            $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
        }

        $ObjSearcher.FindAll() | ForEach-Object {
            $CompProps = [ordered]@{}
            $CompProps.Add('HostName', "$($_.properties.dnshostname)")
            $CompProps.Add('OperatingSystem', "$($_.properties.operatingsystem)")
            $CompProps.Add('ServicePack', "$($_.properties.operatingsystemservicepack)")
            $CompProps.Add('Version', "$($_.properties.operatingsystemversion)")
            $CompProps.Add('DN', "$($_.properties.distinguishedname)")
            $CompProps.Add('Created', [datetime]"$($_.properties.whencreated)")
            $CompProps.Add('LastModified', [datetime]"$($_.properties.whenchanged)")
            $CompProps.Add('IPAddress',([System.Net.Dns]::GetHostAddresses("$($_.properties.dnshostname)")))

            [pscustomobject]$CompProps
         }
        
    }

    End
    {

    }
}


<#
.Synopsis
   Gets a list of Domain users and their details using ADSI.
.DESCRIPTION
   Gets a list of Domain users and their details using ADSI. If the machine it is ran from is
   in the domain and no Domain Controller is specified it will run with the privelages of the user.
   Support the use of alternate user credentials when ran against a domain controller.
.EXAMPLE
   Get-AuditDSUserAcount -Credential (Get-Credential) -DomainController 192.168.10.10
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:


SAMAccount : Administrator
Description : Built-in account for administering the computer/domain
UserPrincipal : Administrator@acmelabs.com
DN : CN=Administrator,CN=Users,DC=acmelabs,DC=com
Created : 1/12/2013 2:06:53 AM
LastModified : 9/10/2013 4:00:28 AM
PasswordLastSet : 8/20/2013 2:13:07 PM
AccountExpires : <Never>
LastLogon : 9/14/2013 2:47:43 PM
GroupMembership : CN=Organization Management,OU=Microsoft Exchange Security Groups,DC=acmelabs,DC=com CN=Group Policy Creator Owners,CN=Users,DC=acmelabs,DC=com
                  CN=Domain Admins,CN=Users,DC=acmelabs,DC=com CN=Enterprise Admins,CN=Users,DC=acmelabs,DC=com CN=Schema Admins,CN=Users,DC=acmelabs,DC=com
                  CN=Administrators,CN=Builtin,DC=acmelabs,DC=com
SID : S-1-5-21-3435989536-2782530369-1314837659-500

SAMAccount : Guest
Description : Built-in account for guest access to the computer/domain
UserPrincipal :
DN : CN=Guest,CN=Users,DC=acmelabs,DC=com
Created : 1/12/2013 2:06:53 AM
LastModified : 1/12/2013 2:06:53 AM
PasswordLastSet : 12/31/1600 8:00:00 PM
AccountExpires : <Never>
LastLogon : 12/31/1600 8:00:00 PM
GroupMembership : CN=Guests,CN=Builtin,DC=acmelabs,DC=com
SID : S-1-5-21-3435989536-2782530369-1314837659-501

SAMAccount : krbtgt
Description : Key Distribution Center Service Account
UserPrincipal :
DN : CN=krbtgt,CN=Users,DC=acmelabs,DC=com
Created : 1/12/2013 2:08:47 AM
LastModified : 3/20/2013 4:38:18 PM
PasswordLastSet : 1/11/2013 10:08:47 PM
AccountExpires : <Never>
LastLogon : 12/31/1600 8:00:00 PM
GroupMembership : CN=Denied RODC Password Replication Group,CN=Users,DC=acmelabs,DC=com
SID : S-1-5-21-3435989536-2782530369-1314837659-502

SAMAccount : cperez
Description :
UserPrincipal : cperez@acmelabs.com
DN : CN=carlos Perez,CN=Users,DC=acmelabs,DC=com
Created : 1/13/2013 9:32:18 PM
LastModified : 7/3/2013 1:34:00 AM
PasswordLastSet : 1/13/2013 5:32:18 PM
AccountExpires : <Never>
LastLogon : 6/26/2013 7:24:53 PM
GroupMembership :
SID : S-1-5-21-3435989536-2782530369-1314837659-1604
#>

function Get-AuditDSUserAcount
{
    [CmdletBinding(DefaultParametersetName="Default")]
    Param(
        [Parameter(ParameterSetName='Modified')]
        [Parameter(ParameterSetName='Created')]
        [Parameter(ParameterSetName='Default')]
        [Parameter(Mandatory=$false,
        HelpMessage="Credentials to use when connecting to a Domain Controller.")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [Parameter(ParameterSetName='Modified')]
        [Parameter(ParameterSetName='Created')]
        [Parameter(ParameterSetName='Default')]
        [Parameter(Mandatory=$false,
        HelpMessage="Domain controller for Domain and Site that you want to query against.")]
        [string]$DomainController,

        [Parameter(ParameterSetName='Modified')]
        [Parameter(ParameterSetName='Created')]
        [Parameter(ParameterSetName='Default')]
        [Parameter(Mandatory=$false,
        HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
        [int]$Limit = 1000,

        [Parameter(ParameterSetName='Modified')]
        [Parameter(ParameterSetName='Created')]
        [Parameter(ParameterSetName='Default')]
        [Parameter(Mandatory=$false,
        HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
        [ValidateSet("Subtree","OneLevel","Base")]
        [string]$SearchScope = "Subtree",

        [Parameter(ParameterSetName='Modified')]
        [Parameter(ParameterSetName='Created')]
        [Parameter(ParameterSetName='Default')]
        [Parameter(Mandatory=$false,
        HelpMessage="Distinguished Name Path to limit search to.")]
        [string]$SearchDN,

        [Parameter(ParameterSetName='Modified',
        HelpMessage="Date to search for users mofied on or after this date.")]
        [datetime]$ModifiedAfter,

        [Parameter(ParameterSetName='Modified',
        HelpMessage="Date to search for users mofied on or before this date.")]
        [datetime]$ModifiedBefore,

        [Parameter(ParameterSetName='Created',
        HelpMessage="Date to search for users created on or after this date.")]
        [datetime]$CreatedAfter,

        [Parameter(ParameterSetName='Created',
        HelpMessage="Date to search for users created on or after this date.")]
        [datetime]$CreatedBefore
    )

    Begin
    {
        if ($DomainController -and $Credential.GetNetworkCredential().Password)
        {
            $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
        else
        {
            $objDomain = [ADSI]""  
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
    }

    Process
    {
        $SAMAccountFilter = "(sAMAccountType=805306368)"

        # Filter for modification time
        if ($ModifiedAfter -and $ModifiedBefore)
        {
            $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($ModifiedAfter.ToString("yyyyMMddhhmmss.sZ")))(whenChanged<=$($ModifiedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
        }
        elseif ($ModifiedAfter)
        {
            $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($ModifiedAfter.ToString("yyyyMMddhhmmss.sZ"))))"
        }
        elseif ($ModifiedBefore)
        {
            $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged<=$($ModifiedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
        }

        # Fileter for creation time
        if ($CreatedAfter -and $CreatedBefore)
        {
            $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($CreatedAfter.ToString("yyyyMMddhhmmss.sZ")))(whenChanged<=$($CreatedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
        }
        elseif ($CreatedAfter)
        {
            $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($CreatedAfter.ToString("yyyyMMddhhmmss.sZ"))))"
        }
        elseif ($CreatedBefore)
        {
            $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged<=$($CreatedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
        }
        
        # Search parameters
        $ObjSearcher.PageSize = $Limit
        $ObjSearcher.Filter = $SAMAccountFilter
        $ObjSearcher.SearchScope = $SearchScope

        if ($SearchDN)
        {
            $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
        }

        $ObjSearcher.FindAll() | ForEach-Object {
            $UserProps = [ordered]@{}
            $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
            $UserProps.Add('Description', "$($_.properties.description)")
            $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)")
            $UserProps.Add('DN', "$($_.properties.distinguishedname)")
            $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
            $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
            $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
            $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)"
                If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks))
                {
                    $AcctExpires = "<Never>"
                }
                Else
                {
                    $Date = [DateTime]$exval
                    $AcctExpires = $Date.AddYears(1600).ToLocalTime()
                }
                $AcctExpires
            
            }))
            $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
            $UserProps.Add('GroupMembership', "$($_.properties.memberof)")
            $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")
        $UserProps.Add('PropertyNames', "$($_.properties.PropertyNames)")
        
            [pscustomobject]$UserProps
            }
    }
}



<#
.Synopsis
   Gets a list of Domain users and their details using ADSI.
.DESCRIPTION
   Gets a list of Domain users and their details using ADSI. If the machine it is ran from is
   in the domain and no Domain Controller is specified it will run with the privelages of the user.
   Support the use of alternate user credentials when ran against a domain controller.
.EXAMPLE
   Get-AuditDSLockedUserAcount -DomainController 192.168.10.10 -Credential (Get-Credential)
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:

SAMAccount : lockeduser
Description :
UserPrincipal : lockeduser@acmelabs.com
DN : CN=lockeduser,CN=Users,DC=acmelabs,DC=com
Created : 6/27/2013 8:23:20 PM
LastModified : 9/15/2013 12:40:13 AM
PasswordLastSet : 6/27/2013 4:23:20 PM
AccountExpires : <Never>
LastLogon : 12/31/1600 8:00:00 PM
GroupMembership :
SID : S-1-5-21-3435989536-2782530369-1314837659-1614

#>

function Get-AuditDSLockedUserAcount
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false,
        HelpMessage="Credentials to use when connecting to a Domain Controller.")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [Parameter(Mandatory=$false,
        HelpMessage="Domain controller for Domain and Site that you want to query against.")]
        [string]$DomainController,

        [Parameter(Mandatory=$false,
        HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
        [int]$Limit = 1000,

        [Parameter(Mandatory=$false,
        HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
        [ValidateSet("Subtree","OneLevel","Base")]
        [string]$SearchScope = "Subtree",

        [Parameter(Mandatory=$false,
        HelpMessage="Distinguished Name Path to limit search to.")]
        [string]$SearchDN
    )

    Begin
    {
        if ($DomainController -and $Credential.GetNetworkCredential().Password)
        {
            $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
        else
        {
            $objDomain = [ADSI]""  
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
    }

    Process
    {
        $SAMAccountFilter = "(&(sAMAccountType=805306368)(lockoutTime>=1))"
        $ObjSearcher.PageSize = $Limit
        $ObjSearcher.Filter = $SAMAccountFilter
        $ObjSearcher.SearchScope = $SearchScope

        if ($SearchDN)
        {
            $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
        }

        $ObjSearcher.FindAll() | ForEach-Object {
            $UserProps = [ordered]@{}
            $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
            $UserProps.Add('Description', "$($_.properties.description)")
            $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)")
            $UserProps.Add('DN', "$($_.properties.distinguishedname)")
            $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
            $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
            $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
            $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)"
                If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks))
                {
                    $AcctExpires = "<Never>"
                }
                Else
                {
                    $Date = [DateTime]$exval
                    $AcctExpires = $Date.AddYears(1600).ToLocalTime()
                }
                $AcctExpires
            
            }))
            $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
            $UserProps.Add('GroupMembership', "$($_.properties.memberof)")
            $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")

            [pscustomobject]$UserProps
            }
    }
}


function Get-AuditDSDisabledUserAcount
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false,
        HelpMessage="Credentials to use when connecting to a Domain Controller.")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [Parameter(Mandatory=$false,
        HelpMessage="Domain controller for Domain and Site that you want to query against.")]
        [string]$DomainController,

        [Parameter(Mandatory=$false,
        HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
        [int]$Limit = 1000,

        [Parameter(Mandatory=$false,
        HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
        [ValidateSet("Subtree","OneLevel","Base")]
        [string]$SearchScope = "Subtree",

        [Parameter(Mandatory=$false,
        HelpMessage="Distinguished Name Path to limit search to.")]
        [string]$SearchDN
    )

    Begin
    {
        if ($DomainController -and $Credential.GetNetworkCredential().Password)
        {
            $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
        else
        {
            $objDomain = [ADSI]""  
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
    }

    Process
    {
        $SAMAccountFilter = "(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=2))"
        $ObjSearcher.PageSize = $Limit
        $ObjSearcher.Filter = $SAMAccountFilter
        $ObjSearcher.SearchScope = $SearchScope

        if ($SearchDN)
        {
            $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
        }

        $ObjSearcher.FindAll() | ForEach-Object {
            $UserProps = [ordered]@{}
            $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
            $UserProps.Add('Description', "$($_.properties.description)")
            $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)")
            $UserProps.Add('DN', "$($_.properties.distinguishedname)")
            $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
            $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
            $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
            $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)"
                If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks))
                {
                    $AcctExpires = "<Never>"
                }
                Else
                {
                    $Date = [DateTime]$exval
                    $AcctExpires = $Date.AddYears(1600).ToLocalTime()
                }
                $AcctExpires
            
            }))
            $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
            $UserProps.Add('GroupMembership', "$($_.properties.memberof)")
            $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")

            [pscustomobject]$UserProps
            }
    }
}


function Get-AuditDSDeletedAccount
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false,
        HelpMessage="Credentials to use when connecting to a Domain Controller.")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [Parameter(Mandatory=$false,
        HelpMessage="Domain controller for Domain and Site that you want to query against.")]
        [string]$DomainController,

        [Parameter(Mandatory=$false,
        HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
        [int]$Limit = 1000,

        [Parameter(Mandatory=$false,
        HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
        [ValidateSet("Subtree","OneLevel","Base")]
        [string]$SearchScope = "Subtree",

        [Parameter(Mandatory=$false,
        HelpMessage="Distinguished Name Path to limit search to.")]
        [string]$SearchDN
    )

    Begin
    {
        if ($DomainController -and $Credential.GetNetworkCredential().Password)
        {
            $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
        else
        {
            $objDomain = [ADSI]""  
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
        }
    }

    Process
    {
        $SAMAccountFilter = "(&(objectClass=user)(isDeleted=*))"
        $ObjSearcher.PageSize = $Limit
        $ObjSearcher.Filter = $SAMAccountFilter
        $ObjSearcher.SearchScope = $SearchScope
        $objSearcher.Tombstone = $true

        if ($SearchDN)
        {
            $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
        }

        $ObjSearcher.FindAll() | ForEach-Object {
            $UserProps = [ordered]@{}
            $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")

            $UserProps.Add('DN', "$($_.properties.distinguishedname)")
            $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
            $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
            $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
            $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
            $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")
            $UserProps.Add('LastKnownParent', "$($_.properties.lastknownparent)")
            [pscustomobject]$UserProps
            }
    }
}


function Get-AuditInstallSoftware
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [string]$ComputerName = $env:COMPUTERNAME
    )
    begin
    {
        
    }
    Process
    {
        # Set initial values
        $reg = Get-WmiObject -List "StdRegprov" -ComputerName $computername -Credential $Credential
        $x86SoftInstallKey = "Software\Microsoft\Windows\CurrentVersion\Uninstall"
        $x64SoftInstallkey = "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
        $data = $reg.EnumKey(2147483650,$x86SoftInstallKey)
        if ($data.ReturnValue -eq 0)
        {
            $x86keys = $data.snames
            $HKSoftKeys = $reg.EnumKey(2147483650,"SOFTWARE").snames
            if ($HKSoftKeys -contains "Wow6432Node")
            {
                $x64keys = $reg.EnumKey(2147483650,$x64SoftInstallkey).snames
            }
        }
        else
        {
            Write-Error "Failed to connect to remote server vial WMI to pull registry information"
            return
        }
        
        $x86keys | foreach {
            $sName = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'DisplayName')).svalue 
            if ($sName)
            {
                $sVersion = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'DisplayVersion')).svalue 
                $sInstallDate = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'InstallDate')).svalue 
                $sPublisher = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'Publisher')).svalue 
                $SoftProps = [ordered]@{Name = $sName; Version = $sVersion; Publisher = $sPublisher; InstallDate = $sInstallDate; PSComputerName = $ComputerName}
                [pscustomobject]$SoftProps
            }
        }

        if ($x64keys)
        {
            $x64keys | foreach {   
                $sName = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'DisplayName')).svalue 
                if ($sName)
                {
                    $sVersion = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'DisplayVersion')).svalue 
                    $sInstallDate = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'InstallDate')).svalue 
                    $sPublisher = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'Publisher')).svalue 
                    $SoftProps = [ordered]@{Name = $sName; Version = $sVersion; Publisher = $sPublisher; InstallDate = $sInstallDate; PSComputerName = $ComputerName}
                    [pscustomobject]$SoftProps
                }
            }
        }
    }
    End
    {
    }
}


function Get-AuditPrefechList
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [string]$ComputerName = $env:COMPUTERNAME
    )
    $winInfo = (Get-WmiObject -query "SELECT WindowsDirectory from Win32_OperatingSystem"  -ComputerName $ComputerName -Credential $Credential).WindowsDirectory.split("\")
    if ($winInfo)
    {
        $pfquery = "SELECT Caption,CreationDate,LastAccessed,LastModified FROM CIM_DataFile WHERE Drive = '$($winInfo[0])' and Path = '\\$($winInfo[1])\\prefetch\\' AND Extension = 'pf'"
        if ($pfquery)
        {
            Get-WmiObject -Query $pfquery  -ComputerName $ComputerName -Credential $Credential | ForEach-Object {
                $pfprops = [ordered]@{
                    Filename = $_.Caption
                    CreationDate = $_.ConvertToDateTime($_.CreationDate)
                    LastAccessed = $_.ConvertToDateTime($_.LastAccessed)
                    LastModified = $_.ConvertToDateTime($_.LastModified)
                }
                [pscustomobject]$pfprops
            }
        }
        else
        {
            Write-Warning "Could not find pf files in the prefetch folder."
        }
    }
    else
    {
        Write-Warning "Could not connect to WMI on the remote system."
    }
}


<#
    .SYSNOPSIS
        Retrieves the timestamps for a given file.

    .DESCRIPTION
        Retrieves the timestamps for a given file. This not only shows the LastAccess, LastWrite and Creation timestamps,
        but also shows the Entrie Modified timestamp, which is not viewable just by looking at the properties of a file.

    .PARAMETER File
        Name of the file to get timestamps from.

    .NOTES
        Name: Get-AuditFileTimeStamp
        Author: Boe Prox
        DateCreated: 26 Feb 2013
        DateModified: 26 Feb 2013
        Version: 1.0 - Initial Creation

    .LINK
        http://learn-powershell.net

    .INPUTS
        System.String

    .OUPUTS
        None

    .EXAMPLE
        Get-AuditFileTimeStamp -File 'SystemError.txt'
        CreationDate : 2/13/2013 7:56:13 AM
        EntrieModifiedTime : 2/26/2013 8:49:28 AM
        ModifiedTime : 2/13/2013 7:56:13 AM
        AccessTime : 2/26/2013 8:48:00 AM
        FileName : C:\users\Administrator\desktop\SystemError.txt


        Description
        -----------
        Displays all timestamps for the file SystemError.txt


#>

Function Get-AuditFileTimeStamp 
{
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline = $True)]
        [string[]]$File 
    )
    Begin {
        #region Debug Information
        $PSBoundParameters.GetEnumerator() | ForEach {
            Write-Verbose ("{0}" -f $_)
        }
        Write-Verbose ("Using ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
        #endregion Debug Information


        #region Create reference variables
        $creationTime = (Get-Date)
        $lastAccessTime = (Get-Date)
        $lastWriteTime = (Get-Date)
        $changeTime = (Get-Date)
        $errorMsg = $null
        #endregion Create reference variables
    }
    Process {
        #region Check file name
        ForEach ($item in $File) {
            If (-Not ([uri]$item).IsAbsoluteUri) {
                Write-Verbose ("{0} is not a full path, using current directory: {1}" -f $item,$pwd)
                $item = (Join-Path $pwd ($item -replace "\.\\",""))
            }
            #endregion Check file name

            #region Get file timestamps
            $return = [NT]::GetFourFileTimes($item,
                                  [ref]$creationTime,
                                  [ref]$lastAccessTime,
                                  [ref]$lastWriteTime,
                                  [ref]$changeTime,
                                  [ref]$errorMsg
                                  )
            If ($return) {
                If (-Not $errorMsg) {
                    $object = New-Object PSObject -Property @{
                        FileName = $item
                        CreationDate = $creationTime
                        ModifiedTime = $lastWriteTime
                        AccessTime = $lastAccessTime 
                        EntrieModifiedTime = $changeTime
                    }
                    $object.pstypenames.insert(0,'System.File.TimeStamp')
                    Write-Output $object
                } Else {
                    Write-Warning ("{0}" -f $errorMsg)
                }
            } Else {
                Write-Warning ("An issue occurred querying the timestamp!")
            }
        }
        #endregion Get file timestamps
    }
    End {}
}


 <#
    .SYNOPSIS
    Retrieves the last write time of the supplied registry key

    .DESCRIPTION
    The Registry data that a hive stores in containers are called cells. A cell
    can hold a key, a value, a security descriptor, a list of subkeys, or a
    list of key values.

    Get-RegKeyLastWriteTime retrieves the LastWriteTime through a pointer to the
    FILETIME structure that receives the time at which the enumerated subkey was
    last written. Values do not contain a LastWriteTime property, but changes to
    child values update the parent keys lpftLastWriteTime.
    
    The LastWriteTime is updated when a key is created, modified, accessed, or
    deleted.

    .PARAMETER ComputerName
    Computer name to query

    .PARAMETER Key
    Root Key to query

    HKCR - Symbolic link to HKEY_LOCAL_MACHINE \SOFTWARE \Classes.
    HKCU - Symbolic link to a key under HKEY_USERS representing a user's profile
    hive.
    HKLM - Placeholder with no corresponding physical hive. This key contains
    other keys that are hives.
    HKU - Placeholder that contains the user-profile hives of logged-on
    accounts.
    HKCC - Symbolic link to the key of the current hardware profile

    .PARAMETER SubKey
    Registry Key to query

    .EXAMPLE
    Get-AuditRegKeyLastWriteTime -ComputerName testwks -Key HKLM -SubKey Software

        .EXAMPLE
    Get-AuditRegKeyLastWriteTime -ComputerName testwks1,testwks2 -SubKey Software

    .EXAMPLE
    Get-AuditRegKeyLastWriteTime -SubKey Software\Microsoft

    .EXAMPLE
    "testwks1","testwks2" | Get-RegKeyLastWriteTime -SubKey Software\Microsoft `
    \Windows\CurrentVersion

    .NOTES
    NAME: Get-RegKeyLastWriteTime
    AUTHOR: Shaun Hess
    VERSION: 1.0
    LASTEDIT: 01JUL2011
    LICENSE: Creative Commons Attribution 3.0 Unported License
    (http://creativecommons.org/licenses/by/3.0/)

    .LINK
    http://www.shaunhess.com
    #>
   
function Get-AuditRegKeyLastWriteTime 
{            
    [CmdletBinding()]            
            
    param(            
        [parameter(            
        ValueFromPipeline=$true,            
        ValueFromPipelineByPropertyName=$true)]            
        [Alias("CN","__SERVER","Computer","CNAME")]            
        [string[]]$ComputerName=$env:ComputerName,            
        [string]$Key = "HKLM",            
        [string]$SubKey            
    )            
            
    BEGIN
    {            
        switch ($Key) {            
           "HKCR" { $searchKey = 0x80000000} #HK Classes Root
           "HKCU" { $searchKey = 0x80000001} #HK Current User
           "HKLM" { $searchKey = 0x80000002} #HK Local Machine
           "HKU"  { $searchKey = 0x80000003} #HK Users
           "HKCC" { $searchKey = 0x80000005} #HK Current Config
           default {            
           "Invalid Key. Use one of the following options:
                    HKCR, HKCU, HKLM, HKU, HKCC"
}            
        }            
            
        $KEYQUERYVALUE = 0x1            
        $KEYREAD = 0x19            
        $KEYALLACCESS = 0x3F            
    }            
    PROCESS 
    {            
        foreach($computer in $ComputerName) {            
              
        $sig0 = @'
[DllImport("advapi32.dll", SetLastError = true)]
  public static extern int RegConnectRegistry(
      string lpMachineName,
    int hkey,
    ref int phkResult);
'@
            
        $type0 = Add-Type -MemberDefinition $sig0 -Name Win32Utils -Namespace RegConnectRegistry -Using System.Text -PassThru            
            
        $sig1 = @'
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
  public static extern int RegOpenKeyEx(
    int hKey,
    string subKey,
    int ulOptions,
    int samDesired,
    out int hkResult);
'@
            
        $type1 = Add-Type -MemberDefinition $sig1 -Name Win32Utils -Namespace RegOpenKeyEx -Using System.Text -PassThru            
            
        $sig2 = @'
[DllImport("advapi32.dll", EntryPoint = "RegEnumKeyEx")]
extern public static int RegEnumKeyEx(
    int hkey,
    int index,
    StringBuilder lpName,
    ref int lpcbName,
    int reserved,
    int lpClass,
    int lpcbClass,
    out long lpftLastWriteTime);
'@
            
        $type2 = Add-Type -MemberDefinition $sig2 -Name Win32Utils -Namespace RegEnumKeyEx -Using System.Text -PassThru            
            
        $sig3 = @'
[DllImport("advapi32.dll", SetLastError=true)]
public static extern int RegCloseKey(
    int hKey);
'@
            
        $type3 = Add-Type -MemberDefinition $sig3 -Name Win32Utils -Namespace RegCloseKey -Using System.Text -PassThru            
            
            
          $hKey = new-object int            
          $hKeyref = new-object int            
          $searchKeyRemote = $type0::RegConnectRegistry($computer, $searchKey, ` [ref]$hKey)            
          $result = $type1::RegOpenKeyEx($hKey, $SubKey, 0, $KEYREAD, ` [ref]$hKeyref)            
            
          #initialize variables
          $builder = New-Object System.Text.StringBuilder 1024            
          $index = 0            
          $length = [int] 1024            
          $time = New-Object Long            
            
          #234 means more info, 0 means success. Either way, keep reading
          while ( 0,234 -contains $type2::RegEnumKeyEx($hKeyref, $index++, $builder, [ref] $length, $null, $null, $null, [ref] $time) )            
          {            
            #create output object
            $o = "" | Select Key, LastWriteTime, ComputerName             
            $o.ComputerName = "$computer"             
            $o.Key = $builder.ToString()            
            # TODO Change to use the time api
            $o.LastWriteTime = (Get-Date $time).AddYears(1600).AddHours(-4)            
            $o            
            
            #reinitialize for next time through the loop
            $length = [int] 1024            
            $builder = New-Object System.Text.StringBuilder 1024            
          }            
            
         $result = $type3::RegCloseKey($hKey);            
         }            
     }            
}