Advertisement
opexxx

Audit.psm1

Feb 23rd, 2014
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .Synopsis
  3.    Enumerates Logged On Sessions on a give host.
  4. .DESCRIPTION
  5.    Enumerates Logged On Sessions on a give host using WMI.
  6. .EXAMPLE
  7.    Get-AuditLogedOnSessions | where {$_.processes.count -gt 0}
  8.  
  9.    Retrieves sessions that have running processes.
  10.  
  11. #>
  12. function Get-AuditLogedOnSessions
  13. {
  14.     [CmdletBinding()]
  15.     Param
  16.     (
  17.         [Parameter(Mandatory=$false)]
  18.         [System.Management.Automation.PSCredential]
  19.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  20.  
  21.         [Parameter(Mandatory=$false)]
  22.         [string]$ComputerName = "localhost"
  23.     )
  24.     begin
  25.     {
  26.         $loggedsessions = @()
  27.         $SessionType = @{
  28.             2  = 'Interactive'
  29.             3  = 'Network'
  30.             4  = 'Batch'
  31.             5  = 'Servie'
  32.             6  = 'Proxy'
  33.             7  = 'Unlock'
  34.             8  = 'NetworkCleartext'
  35.             9  = 'NewCredentials'
  36.             10 = 'Terminal'
  37.             11 = 'CachedInteractive'
  38.             12 = 'CachedTerminal'
  39.             13 = 'CachedUnlock'
  40.         }
  41.     }
  42.     process
  43.     {
  44.         $sessions = Get-WmiObject win32_logonsession -Credential $Credential -ComputerName $ComputerName | select -Unique
  45.  
  46.         foreach ($session in $sessions)
  47.         {
  48.             try{
  49.                 $account = $session.getrelated('win32_useraccount')
  50.                 if ($account -ne $null)
  51.                 {
  52.                    $loggedsessions += [pscustomobject][ordered]@{Name=$account.Caption
  53.                         SID=$account.SID
  54.                         FullName=$account.fullname
  55.                         Created=[System.Management.ManagementDateTimeConverter]::todatetime($session.StartTime)
  56.                         AuthenticationType=$session.AuthenticationPackage
  57.                         LogonType=$SessionType[[int]$session.LogonType]
  58.                         Processes=$session.GetRelated('win32_process')
  59.                    }
  60.                 }
  61.             }
  62.             catch {}
  63.         }
  64.     }
  65.  
  66.     end {$loggedsessions}
  67. }
  68.  
  69.  
  70. <#
  71. .Synopsis
  72.    Gets a list of Domain Computer accounts and their details using ADSI.
  73. .DESCRIPTION
  74.    Gets a list of Domain coputer accounts and their details using ADSI. If the machine it is ran from is
  75.    in the domain and no Domain Controller is specified it will run with the privelages of the user.
  76.    Support the use of alternate user credentials when ran against a domain controller. The host must use
  77.    the same DNS server to be able to reseolve the hostnames to the proper IPAddress.
  78. .EXAMPLE
  79.  
  80. Get-AuditDSComputerAccount -DomainController 192.168.10.10 -Credential (Get-Credential)
  81. cmdlet Get-Credential at command pipeline position 1
  82. Supply values for the following parameters:
  83.  
  84.  
  85. HostName        : DC01.acmelabs.com
  86. OperatingSystem : Windows Server 2012 Standard
  87. ServicePack     :
  88. Version         : 6.2 (9200)
  89. DN              : CN=DC01,OU=Domain Controllers,DC=acmelabs,DC=com
  90. Created         : 1/12/2013 2:08:47 AM
  91. LastModified    : 9/4/2013 7:07:02 PM
  92. IPAddress       : {192.168.10.10}
  93.  
  94. HostName        : DC02.acmelabs.com
  95. OperatingSystem : Windows Server 2008 R2 Enterprise
  96. ServicePack     : Service Pack 1
  97. Version         : 6.1 (7601)
  98. DN              : CN=DC02,OU=Domain Controllers,DC=acmelabs,DC=com
  99. Created         : 1/12/2013 2:15:02 AM
  100. LastModified    : 8/27/2013 9:29:39 AM
  101. IPAddress       : {192.168.10.12}
  102.  
  103. HostName        : WIN701.acmelabs.com
  104. OperatingSystem : Windows 7 Enterprise
  105. ServicePack     : Service Pack 1
  106. Version         : 6.1 (7601)
  107. DN              : CN=WIN701,OU=HR,DC=acmelabs,DC=com
  108. Created         : 1/12/2013 2:45:21 AM
  109. LastModified    : 8/26/2013 6:45:50 PM
  110. IPAddress       : {192.168.10.20}
  111.  
  112. HostName        : WIN702.acmelabs.com
  113. OperatingSystem : Windows 7 Ultimate
  114. ServicePack     : Service Pack 1
  115. Version         : 6.1 (7601)
  116. DN              : CN=WIN702,OU=HR,DC=acmelabs,DC=com
  117. Created         : 1/13/2013 3:27:10 PM
  118. LastModified    : 8/26/2013 6:42:00 PM
  119. IPAddress       : {192.168.10.21}
  120.  
  121. HostName        : WIN801.acmelabs.com
  122. OperatingSystem : Windows 8 Enterprise
  123. ServicePack     :
  124. Version         : 6.2 (9200)
  125. DN              : CN=WIN801,CN=Computers,DC=acmelabs,DC=com
  126. Created         : 1/13/2013 5:48:57 PM
  127. LastModified    : 9/5/2013 5:09:25 AM
  128. IPAddress       : {192.168.10.40}
  129.  
  130. HostName        : WIN2K01.acmelabs.com
  131. OperatingSystem : Windows Server 2012 Standard
  132. ServicePack     :
  133. Version         : 6.2 (9200)
  134. DN              : CN=WIN2K01,CN=Computers,DC=acmelabs,DC=com
  135. Created         : 1/14/2013 4:31:58 PM
  136. LastModified    : 8/25/2013 5:28:07 PM
  137. IPAddress       : {192.168.10.2}
  138.  
  139. HostName        : win2k301.acmelabs.com
  140. OperatingSystem : Windows Server 2003
  141. ServicePack     : Service Pack 2
  142. Version         : 5.2 (3790)
  143. DN              : CN=WIN2K301,CN=Computers,DC=acmelabs,DC=com
  144. Created         : 1/18/2013 12:51:59 PM
  145. LastModified    : 8/15/2013 8:39:43 PM
  146. IPAddress       : {192.168.10.50}
  147. #>
  148. function Get-AuditDSComputerAccount
  149. {
  150.     [CmdletBinding()]
  151.     Param(
  152.         [Parameter(Mandatory=$false,
  153.         HelpMessage="Credentials to use when connecting to a Domain Controller.")]
  154.         [System.Management.Automation.PSCredential]
  155.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  156.        
  157.         [Parameter(Mandatory=$false,
  158.         HelpMessage="Domain controller for Domain and Site that you want to query against.")]
  159.         [string]$DomainController,
  160.  
  161.         [Parameter(Mandatory=$false,
  162.         HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
  163.         [int]$Limit = 1000,
  164.  
  165.         [Parameter(Mandatory=$false,
  166.         HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
  167.         [ValidateSet("Subtree","OneLevel","Base")]
  168.         [string]$SearchScope = "Subtree",
  169.  
  170.         [Parameter(Mandatory=$false,
  171.         HelpMessage="Distinguished Name Path to limit search to.")]
  172.  
  173.         [string]$SearchDN
  174.     )
  175.     Begin
  176.     {
  177.         if ($DomainController -and $Credential.GetNetworkCredential().Password)
  178.         {
  179.             $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
  180.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  181.         }
  182.         else
  183.         {
  184.             $objDomain = [ADSI]""  
  185.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  186.         }
  187.     }
  188.  
  189.     Process
  190.     {
  191.         $CompFilter = "(&(objectCategory=Computer))"
  192.         $ObjSearcher.PageSize = $Limit
  193.         $ObjSearcher.Filter = $CompFilter
  194.         $ObjSearcher.SearchScope = "Subtree"
  195.  
  196.         if ($SearchDN)
  197.         {
  198.             $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
  199.         }
  200.  
  201.         $ObjSearcher.FindAll() | ForEach-Object {
  202.             $CompProps = [ordered]@{}
  203.             $CompProps.Add('HostName', "$($_.properties.dnshostname)")
  204.             $CompProps.Add('OperatingSystem', "$($_.properties.operatingsystem)")
  205.             $CompProps.Add('ServicePack', "$($_.properties.operatingsystemservicepack)")
  206.             $CompProps.Add('Version', "$($_.properties.operatingsystemversion)")
  207.             $CompProps.Add('DN', "$($_.properties.distinguishedname)")
  208.             $CompProps.Add('Created', [datetime]"$($_.properties.whencreated)")
  209.             $CompProps.Add('LastModified', [datetime]"$($_.properties.whenchanged)")
  210.             $CompProps.Add('IPAddress',([System.Net.Dns]::GetHostAddresses("$($_.properties.dnshostname)")))
  211.  
  212.             [pscustomobject]$CompProps
  213.          }
  214.        
  215.     }
  216.  
  217.     End
  218.     {
  219.  
  220.     }
  221. }
  222.  
  223.  
  224. <#
  225. .Synopsis
  226.    Gets a list of Domain users and their details using ADSI.
  227. .DESCRIPTION
  228.    Gets a list of Domain users and their details using ADSI. If the machine it is ran from is
  229.    in the domain and no Domain Controller is specified it will run with the privelages of the user.
  230.    Support the use of alternate user credentials when ran against a domain controller.
  231. .EXAMPLE
  232.    Get-AuditDSUserAcount -Credential (Get-Credential) -DomainController 192.168.10.10
  233. cmdlet Get-Credential at command pipeline position 1
  234. Supply values for the following parameters:
  235.  
  236.  
  237. SAMAccount      : Administrator
  238. Description     : Built-in account for administering the computer/domain
  239. UserPrincipal   : Administrator@acmelabs.com
  240. DN              : CN=Administrator,CN=Users,DC=acmelabs,DC=com
  241. Created         : 1/12/2013 2:06:53 AM
  242. LastModified    : 9/10/2013 4:00:28 AM
  243. PasswordLastSet : 8/20/2013 2:13:07 PM
  244. AccountExpires  : <Never>
  245. LastLogon       : 9/14/2013 2:47:43 PM
  246. GroupMembership : CN=Organization Management,OU=Microsoft Exchange Security Groups,DC=acmelabs,DC=com CN=Group Policy Creator Owners,CN=Users,DC=acmelabs,DC=com
  247.                   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
  248.                   CN=Administrators,CN=Builtin,DC=acmelabs,DC=com
  249. SID             : S-1-5-21-3435989536-2782530369-1314837659-500
  250.  
  251. SAMAccount      : Guest
  252. Description     : Built-in account for guest access to the computer/domain
  253. UserPrincipal   :
  254. DN              : CN=Guest,CN=Users,DC=acmelabs,DC=com
  255. Created         : 1/12/2013 2:06:53 AM
  256. LastModified    : 1/12/2013 2:06:53 AM
  257. PasswordLastSet : 12/31/1600 8:00:00 PM
  258. AccountExpires  : <Never>
  259. LastLogon       : 12/31/1600 8:00:00 PM
  260. GroupMembership : CN=Guests,CN=Builtin,DC=acmelabs,DC=com
  261. SID             : S-1-5-21-3435989536-2782530369-1314837659-501
  262.  
  263. SAMAccount      : krbtgt
  264. Description     : Key Distribution Center Service Account
  265. UserPrincipal   :
  266. DN              : CN=krbtgt,CN=Users,DC=acmelabs,DC=com
  267. Created         : 1/12/2013 2:08:47 AM
  268. LastModified    : 3/20/2013 4:38:18 PM
  269. PasswordLastSet : 1/11/2013 10:08:47 PM
  270. AccountExpires  : <Never>
  271. LastLogon       : 12/31/1600 8:00:00 PM
  272. GroupMembership : CN=Denied RODC Password Replication Group,CN=Users,DC=acmelabs,DC=com
  273. SID             : S-1-5-21-3435989536-2782530369-1314837659-502
  274.  
  275. SAMAccount      : cperez
  276. Description     :
  277. UserPrincipal   : cperez@acmelabs.com
  278. DN              : CN=carlos Perez,CN=Users,DC=acmelabs,DC=com
  279. Created         : 1/13/2013 9:32:18 PM
  280. LastModified    : 7/3/2013 1:34:00 AM
  281. PasswordLastSet : 1/13/2013 5:32:18 PM
  282. AccountExpires  : <Never>
  283. LastLogon       : 6/26/2013 7:24:53 PM
  284. GroupMembership :
  285. SID             : S-1-5-21-3435989536-2782530369-1314837659-1604
  286. #>
  287. function Get-AuditDSUserAcount
  288. {
  289.     [CmdletBinding(DefaultParametersetName="Default")]
  290.     Param(
  291.         [Parameter(ParameterSetName='Modified')]
  292.         [Parameter(ParameterSetName='Created')]
  293.         [Parameter(ParameterSetName='Default')]
  294.         [Parameter(Mandatory=$false,
  295.         HelpMessage="Credentials to use when connecting to a Domain Controller.")]
  296.         [System.Management.Automation.PSCredential]
  297.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  298.        
  299.         [Parameter(ParameterSetName='Modified')]
  300.         [Parameter(ParameterSetName='Created')]
  301.         [Parameter(ParameterSetName='Default')]
  302.         [Parameter(Mandatory=$false,
  303.         HelpMessage="Domain controller for Domain and Site that you want to query against.")]
  304.         [string]$DomainController,
  305.  
  306.         [Parameter(ParameterSetName='Modified')]
  307.         [Parameter(ParameterSetName='Created')]
  308.         [Parameter(ParameterSetName='Default')]
  309.         [Parameter(Mandatory=$false,
  310.         HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
  311.         [int]$Limit = 1000,
  312.  
  313.         [Parameter(ParameterSetName='Modified')]
  314.         [Parameter(ParameterSetName='Created')]
  315.         [Parameter(ParameterSetName='Default')]
  316.         [Parameter(Mandatory=$false,
  317.         HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
  318.         [ValidateSet("Subtree","OneLevel","Base")]
  319.         [string]$SearchScope = "Subtree",
  320.  
  321.         [Parameter(ParameterSetName='Modified')]
  322.         [Parameter(ParameterSetName='Created')]
  323.         [Parameter(ParameterSetName='Default')]
  324.         [Parameter(Mandatory=$false,
  325.         HelpMessage="Distinguished Name Path to limit search to.")]
  326.         [string]$SearchDN,
  327.  
  328.         [Parameter(ParameterSetName='Modified',
  329.         HelpMessage="Date to search for users mofied on or after this date.")]
  330.         [datetime]$ModifiedAfter,
  331.  
  332.         [Parameter(ParameterSetName='Modified',
  333.         HelpMessage="Date to search for users mofied on or before this date.")]
  334.         [datetime]$ModifiedBefore,
  335.  
  336.         [Parameter(ParameterSetName='Created',
  337.         HelpMessage="Date to search for users created on or after this date.")]
  338.         [datetime]$CreatedAfter,
  339.  
  340.         [Parameter(ParameterSetName='Created',
  341.         HelpMessage="Date to search for users created on or after this date.")]
  342.         [datetime]$CreatedBefore
  343.     )
  344.  
  345.     Begin
  346.     {
  347.         if ($DomainController -and $Credential.GetNetworkCredential().Password)
  348.         {
  349.             $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
  350.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  351.         }
  352.         else
  353.         {
  354.             $objDomain = [ADSI]""  
  355.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  356.         }
  357.     }
  358.  
  359.     Process
  360.     {
  361.         $SAMAccountFilter = "(sAMAccountType=805306368)"
  362.  
  363.         # Filter for modification time
  364.         if ($ModifiedAfter -and $ModifiedBefore)
  365.         {
  366.             $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($ModifiedAfter.ToString("yyyyMMddhhmmss.sZ")))(whenChanged<=$($ModifiedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
  367.         }
  368.         elseif ($ModifiedAfter)
  369.         {
  370.             $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($ModifiedAfter.ToString("yyyyMMddhhmmss.sZ"))))"
  371.         }
  372.         elseif ($ModifiedBefore)
  373.         {
  374.             $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged<=$($ModifiedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
  375.         }
  376.  
  377.         # Fileter for creation time
  378.         if ($CreatedAfter -and $CreatedBefore)
  379.         {
  380.             $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($CreatedAfter.ToString("yyyyMMddhhmmss.sZ")))(whenChanged<=$($CreatedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
  381.         }
  382.         elseif ($CreatedAfter)
  383.         {
  384.             $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($CreatedAfter.ToString("yyyyMMddhhmmss.sZ"))))"
  385.         }
  386.         elseif ($CreatedBefore)
  387.         {
  388.             $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged<=$($CreatedBefore.ToString("yyyyMMddhhmmss.sZ"))))"
  389.         }
  390.        
  391.         # Search parameters
  392.         $ObjSearcher.PageSize = $Limit
  393.         $ObjSearcher.Filter = $SAMAccountFilter
  394.         $ObjSearcher.SearchScope = $SearchScope
  395.  
  396.         if ($SearchDN)
  397.         {
  398.             $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
  399.         }
  400.  
  401.         $ObjSearcher.FindAll() | ForEach-Object {
  402.             $UserProps = [ordered]@{}
  403.             $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
  404.             $UserProps.Add('Description', "$($_.properties.description)")
  405.             $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)")
  406.             $UserProps.Add('DN', "$($_.properties.distinguishedname)")
  407.             $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
  408.             $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
  409.             $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
  410.             $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)"
  411.                 If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks))
  412.                 {
  413.                     $AcctExpires = "<Never>"
  414.                 }
  415.                 Else
  416.                 {
  417.                     $Date = [DateTime]$exval
  418.                     $AcctExpires = $Date.AddYears(1600).ToLocalTime()
  419.                 }
  420.                 $AcctExpires
  421.            
  422.             }))
  423.             $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
  424.             $UserProps.Add('GroupMembership', "$($_.properties.memberof)")
  425.             $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")
  426.  
  427.             [pscustomobject]$UserProps
  428.             }
  429.     }
  430. }
  431.  
  432.  
  433.  
  434. <#
  435. .Synopsis
  436.    Gets a list of Domain users and their details using ADSI.
  437. .DESCRIPTION
  438.    Gets a list of Domain users and their details using ADSI. If the machine it is ran from is
  439.    in the domain and no Domain Controller is specified it will run with the privelages of the user.
  440.    Support the use of alternate user credentials when ran against a domain controller.
  441. .EXAMPLE
  442.    Get-AuditDSLockedUserAcount -DomainController 192.168.10.10 -Credential (Get-Credential)
  443. cmdlet Get-Credential at command pipeline position 1
  444. Supply values for the following parameters:
  445.  
  446. SAMAccount      : lockeduser
  447. Description     :
  448. UserPrincipal   : lockeduser@acmelabs.com
  449. DN              : CN=lockeduser,CN=Users,DC=acmelabs,DC=com
  450. Created         : 6/27/2013 8:23:20 PM
  451. LastModified    : 9/15/2013 12:40:13 AM
  452. PasswordLastSet : 6/27/2013 4:23:20 PM
  453. AccountExpires  : <Never>
  454. LastLogon       : 12/31/1600 8:00:00 PM
  455. GroupMembership :
  456. SID             : S-1-5-21-3435989536-2782530369-1314837659-1614
  457.  
  458. #>
  459. function Get-AuditDSLockedUserAcount
  460. {
  461.     [CmdletBinding()]
  462.     Param(
  463.         [Parameter(Mandatory=$false,
  464.         HelpMessage="Credentials to use when connecting to a Domain Controller.")]
  465.         [System.Management.Automation.PSCredential]
  466.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  467.        
  468.         [Parameter(Mandatory=$false,
  469.         HelpMessage="Domain controller for Domain and Site that you want to query against.")]
  470.         [string]$DomainController,
  471.  
  472.         [Parameter(Mandatory=$false,
  473.         HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
  474.         [int]$Limit = 1000,
  475.  
  476.         [Parameter(Mandatory=$false,
  477.         HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
  478.         [ValidateSet("Subtree","OneLevel","Base")]
  479.         [string]$SearchScope = "Subtree",
  480.  
  481.         [Parameter(Mandatory=$false,
  482.         HelpMessage="Distinguished Name Path to limit search to.")]
  483.         [string]$SearchDN
  484.     )
  485.  
  486.     Begin
  487.     {
  488.         if ($DomainController -and $Credential.GetNetworkCredential().Password)
  489.         {
  490.             $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
  491.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  492.         }
  493.         else
  494.         {
  495.             $objDomain = [ADSI]""  
  496.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  497.         }
  498.     }
  499.  
  500.     Process
  501.     {
  502.         $SAMAccountFilter = "(&(sAMAccountType=805306368)(lockoutTime>=1))"
  503.         $ObjSearcher.PageSize = $Limit
  504.         $ObjSearcher.Filter = $SAMAccountFilter
  505.         $ObjSearcher.SearchScope = $SearchScope
  506.  
  507.         if ($SearchDN)
  508.         {
  509.             $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
  510.         }
  511.  
  512.         $ObjSearcher.FindAll() | ForEach-Object {
  513.             $UserProps = [ordered]@{}
  514.             $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
  515.             $UserProps.Add('Description', "$($_.properties.description)")
  516.             $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)")
  517.             $UserProps.Add('DN', "$($_.properties.distinguishedname)")
  518.             $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
  519.             $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
  520.             $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
  521.             $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)"
  522.                 If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks))
  523.                 {
  524.                     $AcctExpires = "<Never>"
  525.                 }
  526.                 Else
  527.                 {
  528.                     $Date = [DateTime]$exval
  529.                     $AcctExpires = $Date.AddYears(1600).ToLocalTime()
  530.                 }
  531.                 $AcctExpires
  532.            
  533.             }))
  534.             $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
  535.             $UserProps.Add('GroupMembership', "$($_.properties.memberof)")
  536.             $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")
  537.  
  538.             [pscustomobject]$UserProps
  539.             }
  540.     }
  541. }
  542.  
  543.  
  544. function Get-AuditDSDisabledUserAcount
  545. {
  546.     [CmdletBinding()]
  547.     Param(
  548.         [Parameter(Mandatory=$false,
  549.         HelpMessage="Credentials to use when connecting to a Domain Controller.")]
  550.         [System.Management.Automation.PSCredential]
  551.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  552.        
  553.         [Parameter(Mandatory=$false,
  554.         HelpMessage="Domain controller for Domain and Site that you want to query against.")]
  555.         [string]$DomainController,
  556.  
  557.         [Parameter(Mandatory=$false,
  558.         HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
  559.         [int]$Limit = 1000,
  560.  
  561.         [Parameter(Mandatory=$false,
  562.         HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
  563.         [ValidateSet("Subtree","OneLevel","Base")]
  564.         [string]$SearchScope = "Subtree",
  565.  
  566.         [Parameter(Mandatory=$false,
  567.         HelpMessage="Distinguished Name Path to limit search to.")]
  568.         [string]$SearchDN
  569.     )
  570.  
  571.     Begin
  572.     {
  573.         if ($DomainController -and $Credential.GetNetworkCredential().Password)
  574.         {
  575.             $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
  576.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  577.         }
  578.         else
  579.         {
  580.             $objDomain = [ADSI]""  
  581.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  582.         }
  583.     }
  584.  
  585.     Process
  586.     {
  587.         $SAMAccountFilter = "(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=2))"
  588.         $ObjSearcher.PageSize = $Limit
  589.         $ObjSearcher.Filter = $SAMAccountFilter
  590.         $ObjSearcher.SearchScope = $SearchScope
  591.  
  592.         if ($SearchDN)
  593.         {
  594.             $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
  595.         }
  596.  
  597.         $ObjSearcher.FindAll() | ForEach-Object {
  598.             $UserProps = [ordered]@{}
  599.             $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
  600.             $UserProps.Add('Description', "$($_.properties.description)")
  601.             $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)")
  602.             $UserProps.Add('DN', "$($_.properties.distinguishedname)")
  603.             $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
  604.             $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
  605.             $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
  606.             $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)"
  607.                 If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks))
  608.                 {
  609.                     $AcctExpires = "<Never>"
  610.                 }
  611.                 Else
  612.                 {
  613.                     $Date = [DateTime]$exval
  614.                     $AcctExpires = $Date.AddYears(1600).ToLocalTime()
  615.                 }
  616.                 $AcctExpires
  617.            
  618.             }))
  619.             $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
  620.             $UserProps.Add('GroupMembership', "$($_.properties.memberof)")
  621.             $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")
  622.  
  623.             [pscustomobject]$UserProps
  624.             }
  625.     }
  626. }
  627.  
  628.  
  629. function Get-AuditDSDeletedAccount
  630. {
  631.     [CmdletBinding()]
  632.     Param(
  633.         [Parameter(Mandatory=$false,
  634.         HelpMessage="Credentials to use when connecting to a Domain Controller.")]
  635.         [System.Management.Automation.PSCredential]
  636.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  637.        
  638.         [Parameter(Mandatory=$false,
  639.         HelpMessage="Domain controller for Domain and Site that you want to query against.")]
  640.         [string]$DomainController,
  641.  
  642.         [Parameter(Mandatory=$false,
  643.         HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")]
  644.         [int]$Limit = 1000,
  645.  
  646.         [Parameter(Mandatory=$false,
  647.         HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")]
  648.         [ValidateSet("Subtree","OneLevel","Base")]
  649.         [string]$SearchScope = "Subtree",
  650.  
  651.         [Parameter(Mandatory=$false,
  652.         HelpMessage="Distinguished Name Path to limit search to.")]
  653.         [string]$SearchDN
  654.     )
  655.  
  656.     Begin
  657.     {
  658.         if ($DomainController -and $Credential.GetNetworkCredential().Password)
  659.         {
  660.             $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password
  661.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  662.         }
  663.         else
  664.         {
  665.             $objDomain = [ADSI]""  
  666.             $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain
  667.         }
  668.     }
  669.  
  670.     Process
  671.     {
  672.         $SAMAccountFilter = "(&(objectClass=user)(isDeleted=*))"
  673.         $ObjSearcher.PageSize = $Limit
  674.         $ObjSearcher.Filter = $SAMAccountFilter
  675.         $ObjSearcher.SearchScope = $SearchScope
  676.         $objSearcher.Tombstone = $true
  677.  
  678.         if ($SearchDN)
  679.         {
  680.             $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)")
  681.         }
  682.  
  683.         $ObjSearcher.FindAll() | ForEach-Object {
  684.             $UserProps = [ordered]@{}
  685.             $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)")
  686.  
  687.             $UserProps.Add('DN', "$($_.properties.distinguishedname)")
  688.             $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)")
  689.             $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)")
  690.             $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)"))
  691.             $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)"))
  692.             $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})")
  693.             $UserProps.Add('LastKnownParent', "$($_.properties.lastknownparent)")
  694.             [pscustomobject]$UserProps
  695.             }
  696.     }
  697. }
  698.  
  699.  
  700. function Get-AuditInstallSoftware
  701. {
  702.     [CmdletBinding()]
  703.     Param(
  704.         [Parameter(Mandatory=$false)]
  705.         [System.Management.Automation.PSCredential]
  706.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  707.        
  708.         [string]$ComputerName = $env:COMPUTERNAME
  709.     )
  710.     begin
  711.     {
  712.        
  713.     }
  714.     Process
  715.     {
  716.         # Set initial values
  717.         $reg = Get-WmiObject -List "StdRegprov" -ComputerName $computername -Credential $Credential
  718.         $x86SoftInstallKey = "Software\Microsoft\Windows\CurrentVersion\Uninstall"
  719.         $x64SoftInstallkey = "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
  720.         $data = $reg.EnumKey(2147483650,$x86SoftInstallKey)
  721.         if ($data.ReturnValue -eq 0)
  722.         {
  723.             $x86keys = $data.snames
  724.             $HKSoftKeys = $reg.EnumKey(2147483650,"SOFTWARE").snames
  725.             if ($HKSoftKeys -contains "Wow6432Node")
  726.             {
  727.                 $x64keys = $reg.EnumKey(2147483650,$x64SoftInstallkey).snames
  728.             }
  729.         }
  730.         else
  731.         {
  732.             Write-Error "Failed to connect to remote server vial WMI to pull registry information"
  733.             return
  734.         }
  735.        
  736.         $x86keys | foreach {
  737.             $sName = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'DisplayName')).svalue
  738.             if ($sName)
  739.             {
  740.                 $sVersion = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'DisplayVersion')).svalue
  741.                 $sInstallDate = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'InstallDate')).svalue
  742.                 $sPublisher = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'Publisher')).svalue
  743.                 $SoftProps = [ordered]@{Name = $sName; Version = $sVersion; Publisher = $sPublisher; InstallDate = $sInstallDate; PSComputerName = $ComputerName}
  744.                 [pscustomobject]$SoftProps
  745.             }
  746.         }
  747.  
  748.         if ($x64keys)
  749.         {
  750.             $x64keys | foreach {  
  751.                 $sName = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'DisplayName')).svalue
  752.                 if ($sName)
  753.                 {
  754.                     $sVersion = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'DisplayVersion')).svalue
  755.                     $sInstallDate = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'InstallDate')).svalue
  756.                     $sPublisher = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'Publisher')).svalue
  757.                     $SoftProps = [ordered]@{Name = $sName; Version = $sVersion; Publisher = $sPublisher; InstallDate = $sInstallDate; PSComputerName = $ComputerName}
  758.                     [pscustomobject]$SoftProps
  759.                 }
  760.             }
  761.         }
  762.     }
  763.     End
  764.     {
  765.     }
  766. }
  767.  
  768.  
  769. function Get-AuditPrefechList
  770. {
  771.     [CmdletBinding()]
  772.     Param(
  773.         [Parameter(Mandatory=$false)]
  774.         [System.Management.Automation.PSCredential]
  775.         [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
  776.        
  777.         [string]$ComputerName = $env:COMPUTERNAME
  778.     )
  779.     $winInfo = (Get-WmiObject -query "SELECT WindowsDirectory from Win32_OperatingSystem"  -ComputerName $ComputerName -Credential $Credential).WindowsDirectory.split("\")
  780.     if ($winInfo)
  781.     {
  782.         $pfquery = "SELECT Caption,CreationDate,LastAccessed,LastModified FROM CIM_DataFile WHERE Drive = '$($winInfo[0])' and Path = '\\$($winInfo[1])\\prefetch\\' AND Extension = 'pf'"
  783.         if ($pfquery)
  784.         {
  785.             Get-WmiObject -Query $pfquery  -ComputerName $ComputerName -Credential $Credential | ForEach-Object {
  786.                 $pfprops = [ordered]@{
  787.                     Filename = $_.Caption
  788.                     CreationDate = $_.ConvertToDateTime($_.CreationDate)
  789.                     LastAccessed = $_.ConvertToDateTime($_.LastAccessed)
  790.                     LastModified = $_.ConvertToDateTime($_.LastModified)
  791.                 }
  792.                 [pscustomobject]$pfprops
  793.             }
  794.         }
  795.         else
  796.         {
  797.             Write-Warning "Could not find pf files in the prefetch folder."
  798.         }
  799.     }
  800.     else
  801.     {
  802.         Write-Warning "Could not connect to WMI on the remote system."
  803.     }
  804. }
  805.  
  806.  
  807. <#
  808.     .SYSNOPSIS
  809.         Retrieves the timestamps for a given file.
  810.  
  811.     .DESCRIPTION
  812.         Retrieves the timestamps for a given file. This not only shows the LastAccess, LastWrite and Creation timestamps,
  813.         but also shows the Entrie Modified timestamp, which is not viewable just by looking at the properties of a file.
  814.  
  815.     .PARAMETER File
  816.         Name of the file to get timestamps from.
  817.  
  818.     .NOTES
  819.         Name: Get-AuditFileTimeStamp
  820.         Author: Boe Prox
  821.         DateCreated: 26 Feb 2013
  822.         DateModified: 26 Feb 2013
  823.         Version: 1.0 - Initial Creation
  824.  
  825.     .LINK
  826.         http://learn-powershell.net
  827.  
  828.     .INPUTS
  829.         System.String
  830.  
  831.     .OUPUTS
  832.         None
  833.  
  834.     .EXAMPLE
  835.         Get-AuditFileTimeStamp -File 'SystemError.txt'
  836.         CreationDate   : 2/13/2013 7:56:13 AM
  837.         EntrieModifiedTime     : 2/26/2013 8:49:28 AM
  838.         ModifiedTime  : 2/13/2013 7:56:13 AM
  839.         AccessTime : 2/26/2013 8:48:00 AM
  840.         FileName       : C:\users\Administrator\desktop\SystemError.txt
  841.  
  842.  
  843.         Description
  844.         -----------
  845.         Displays all timestamps for the file SystemError.txt
  846.  
  847.  
  848. #>
  849. Function Get-AuditFileTimeStamp
  850. {
  851.     [cmdletbinding()]
  852.     Param (
  853.         [parameter(ValueFromPipeline = $True)]
  854.         [string[]]$File
  855.     )
  856.     Begin {
  857.         #region Debug Information
  858.         $PSBoundParameters.GetEnumerator() | ForEach {
  859.             Write-Verbose ("{0}" -f $_)
  860.         }
  861.         Write-Verbose ("Using ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
  862.         #endregion Debug Information
  863.  
  864.  
  865.         #region Create reference variables
  866.         $creationTime = (Get-Date)
  867.         $lastAccessTime = (Get-Date)
  868.         $lastWriteTime = (Get-Date)
  869.         $changeTime = (Get-Date)
  870.         $errorMsg = $null
  871.         #endregion Create reference variables
  872.     }
  873.     Process {
  874.         #region Check file name
  875.         ForEach ($item in $File) {
  876.             If (-Not ([uri]$item).IsAbsoluteUri) {
  877.                 Write-Verbose ("{0} is not a full path, using current directory: {1}" -f $item,$pwd)
  878.                 $item = (Join-Path $pwd ($item -replace "\.\\",""))
  879.             }
  880.             #endregion Check file name
  881.  
  882.             #region Get file timestamps
  883.             $return = [NT]::GetFourFileTimes($item,
  884.                                   [ref]$creationTime,
  885.                                   [ref]$lastAccessTime,
  886.                                   [ref]$lastWriteTime,
  887.                                   [ref]$changeTime,
  888.                                   [ref]$errorMsg
  889.                                   )
  890.             If ($return) {
  891.                 If (-Not $errorMsg) {
  892.                     $object = New-Object PSObject -Property @{
  893.                         FileName = $item
  894.                         CreationDate = $creationTime
  895.                         ModifiedTime = $lastWriteTime
  896.                         AccessTime = $lastAccessTime
  897.                         EntrieModifiedTime = $changeTime
  898.                     }
  899.                     $object.pstypenames.insert(0,'System.File.TimeStamp')
  900.                     Write-Output $object
  901.                 } Else {
  902.                     Write-Warning ("{0}" -f $errorMsg)
  903.                 }
  904.             } Else {
  905.                 Write-Warning ("An issue occurred querying the timestamp!")
  906.             }
  907.         }
  908.         #endregion Get file timestamps
  909.     }
  910.     End {}
  911. }
  912.  
  913.  
  914.  <#
  915.     .SYNOPSIS
  916.     Retrieves the last write time of the supplied registry key
  917.  
  918.     .DESCRIPTION
  919.     The Registry data that a hive stores in containers are called cells. A cell
  920.     can hold a key, a value, a security descriptor, a list of subkeys, or a
  921.     list of key values.
  922.  
  923.     Get-RegKeyLastWriteTime retrieves the LastWriteTime through a pointer to the
  924.     FILETIME structure that receives the time at which the enumerated subkey was
  925.     last written. Values do not contain a LastWriteTime property, but changes to
  926.     child values update the parent keys lpftLastWriteTime.
  927.    
  928.     The LastWriteTime is updated when a key is created, modified, accessed, or
  929.     deleted.
  930.  
  931.     .PARAMETER ComputerName
  932.     Computer name to query
  933.  
  934.     .PARAMETER Key
  935.     Root Key to query
  936.  
  937.     HKCR - Symbolic link to HKEY_LOCAL_MACHINE \SOFTWARE \Classes.
  938.     HKCU - Symbolic link to a key under HKEY_USERS representing a user's profile
  939.     hive.
  940.     HKLM - Placeholder with no corresponding physical hive. This key contains
  941.     other keys that are hives.
  942.     HKU  - Placeholder that contains the user-profile hives of logged-on
  943.     accounts.
  944.     HKCC - Symbolic link to the key of the current hardware profile
  945.  
  946.     .PARAMETER SubKey
  947.     Registry Key to query
  948.  
  949.     .EXAMPLE
  950.     Get-AuditRegKeyLastWriteTime -ComputerName testwks -Key HKLM -SubKey Software
  951.  
  952.         .EXAMPLE
  953.     Get-AuditRegKeyLastWriteTime -ComputerName testwks1,testwks2 -SubKey Software
  954.  
  955.     .EXAMPLE
  956.     Get-AuditRegKeyLastWriteTime -SubKey Software\Microsoft
  957.  
  958.     .EXAMPLE
  959.     "testwks1","testwks2" | Get-RegKeyLastWriteTime -SubKey Software\Microsoft `
  960.     \Windows\CurrentVersion
  961.  
  962.     .NOTES
  963.     NAME: Get-RegKeyLastWriteTime
  964.     AUTHOR: Shaun Hess
  965.     VERSION: 1.0
  966.     LASTEDIT: 01JUL2011
  967.     LICENSE: Creative Commons Attribution 3.0 Unported License
  968.     (http://creativecommons.org/licenses/by/3.0/)
  969.  
  970.     .LINK
  971.     http://www.shaunhess.com
  972.     #>  
  973. function Get-AuditRegKeyLastWriteTime
  974. {            
  975.     [CmdletBinding()]            
  976.            
  977.     param(            
  978.         [parameter(            
  979.         ValueFromPipeline=$true,            
  980.         ValueFromPipelineByPropertyName=$true)]            
  981.         [Alias("CN","__SERVER","Computer","CNAME")]            
  982.         [string[]]$ComputerName=$env:ComputerName,            
  983.         [string]$Key = "HKLM",            
  984.         [string]$SubKey            
  985.     )            
  986.            
  987.     BEGIN
  988.     {            
  989.         switch ($Key) {            
  990.            "HKCR" { $searchKey = 0x80000000} #HK Classes Root            
  991.            "HKCU" { $searchKey = 0x80000001} #HK Current User            
  992.            "HKLM" { $searchKey = 0x80000002} #HK Local Machine            
  993.            "HKU"  { $searchKey = 0x80000003} #HK Users            
  994.            "HKCC" { $searchKey = 0x80000005} #HK Current Config            
  995.            default {            
  996.            "Invalid Key. Use one of the following options:
  997.                     HKCR, HKCU, HKLM, HKU, HKCC"}            
  998.         }            
  999.            
  1000.         $KEYQUERYVALUE = 0x1            
  1001.         $KEYREAD = 0x19            
  1002.         $KEYALLACCESS = 0x3F            
  1003.     }            
  1004.     PROCESS
  1005.     {            
  1006.         foreach($computer in $ComputerName) {            
  1007.              
  1008.         $sig0 = @'
  1009. [DllImport("advapi32.dll", SetLastError = true)]
  1010.  public static extern int RegConnectRegistry(
  1011.     string lpMachineName,
  1012.     int hkey,
  1013.     ref int phkResult);
  1014. '@            
  1015.         $type0 = Add-Type -MemberDefinition $sig0 -Name Win32Utils -Namespace RegConnectRegistry -Using System.Text -PassThru            
  1016.            
  1017.         $sig1 = @'
  1018. [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
  1019.  public static extern int RegOpenKeyEx(
  1020.    int hKey,
  1021.    string subKey,
  1022.    int ulOptions,
  1023.    int samDesired,
  1024.    out int hkResult);
  1025. '@            
  1026.         $type1 = Add-Type -MemberDefinition $sig1 -Name Win32Utils -Namespace RegOpenKeyEx -Using System.Text -PassThru            
  1027.            
  1028.         $sig2 = @'
  1029. [DllImport("advapi32.dll", EntryPoint = "RegEnumKeyEx")]
  1030. extern public static int RegEnumKeyEx(
  1031.    int hkey,
  1032.    int index,
  1033.    StringBuilder lpName,
  1034.    ref int lpcbName,
  1035.    int reserved,
  1036.    int lpClass,
  1037.    int lpcbClass,
  1038.    out long lpftLastWriteTime);
  1039. '@            
  1040.         $type2 = Add-Type -MemberDefinition $sig2 -Name Win32Utils -Namespace RegEnumKeyEx -Using System.Text -PassThru            
  1041.            
  1042.         $sig3 = @'
  1043. [DllImport("advapi32.dll", SetLastError=true)]
  1044. public static extern int RegCloseKey(
  1045.    int hKey);
  1046. '@            
  1047.         $type3 = Add-Type -MemberDefinition $sig3 -Name Win32Utils -Namespace RegCloseKey -Using System.Text -PassThru            
  1048.            
  1049.            
  1050.           $hKey = new-object int            
  1051.           $hKeyref = new-object int            
  1052.           $searchKeyRemote = $type0::RegConnectRegistry($computer, $searchKey, `  [ref]$hKey)            
  1053.           $result = $type1::RegOpenKeyEx($hKey, $SubKey, 0, $KEYREAD, `  [ref]$hKeyref)            
  1054.            
  1055.           #initialize variables            
  1056.           $builder = New-Object System.Text.StringBuilder 1024            
  1057.           $index = 0            
  1058.           $length = [int] 1024            
  1059.           $time = New-Object Long            
  1060.            
  1061.           #234 means more info, 0 means success. Either way, keep reading            
  1062.           while ( 0,234 -contains $type2::RegEnumKeyEx($hKeyref, $index++, $builder, [ref] $length, $null, $null, $null, [ref] $time) )            
  1063.           {            
  1064.             #create output object            
  1065.             $o = "" | Select Key, LastWriteTime, ComputerName            
  1066.             $o.ComputerName = "$computer"            
  1067.             $o.Key = $builder.ToString()            
  1068.             # TODO Change to use the time api            
  1069.             $o.LastWriteTime = (Get-Date $time).AddYears(1600).AddHours(-4)            
  1070.             $o            
  1071.            
  1072.             #reinitialize for next time through the loop            
  1073.             $length = [int] 1024            
  1074.             $builder = New-Object System.Text.StringBuilder 1024            
  1075.           }            
  1076.            
  1077.          $result = $type3::RegCloseKey($hKey);            
  1078.          }            
  1079.      }            
  1080. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement