Extract user properties with Group Membership

Scenario: User account disabled and group membership removed.
In all organisations where Active Directory is deployed, some form of user termination process is followed. User accounts of ex-employees are disabled, their group membership is cleared and these disabled accounts are left to complete their retention period before they are finally deleted. Once in a while we are asked to re-activate the account along with all the access they had as a result of their group membership. In such a scenario, restoring the group membership to what it was, is not easy. Below script can be set as a scheduled task to extract various user properties along with the group membership. The archives can then be used to restore the account along with group membership.

1
2
3
4
5
6
7
8
9
$date = Get-Date -UFormat "%Y-%m-%d"
$OUs= 'ou=employees,dc=domain,dc=net','ou=contractors,dc=domain,dc=net'
ForEach($OU in $OUs){
Get-ADUser -SearchBase 'ou=employees,dc=domain,dc=net' -Filter *  -Properties * | Select-Object name,CanonicalName,City,CN,co,Country,Created,Department,Description,DisplayName,DistinguishedName,EmailAddress,ipPhone,HomePhone,Manager,mobile,objectSid,OfficePhone,PasswordLastSetStreetAddress,title,whenchanged,whencreated,workshift,@{Name="LastLogonTimeStamp";Expression={([datetime]::FromFileTime($_.LastLogonTimeStamp))}},@{n='memberof';e={ ( $_.memberof | % { (Get-ADObject $_).Name }) -join ";" }} | Export-Csv "C:\ADExtracts\UserExtracts\$($date)_UserExtract.csv" -Append -NoTypeInformation
}
Compress-Archive -Path "C:\ADExtracts\UserExtracts\$($date)_UserExtract.csv" -DestinationPath "C:\ADExtracts\UserExtracts\$($date)_UserExtract.zip"
Remove-Item -Path "C:\ADExtracts\UserExtracts\$($date)_UserExtract.csv"
## Delete files older than the $limit.
Get-ChildItem "C:\ADExtracts\UserExtracts" -Recurse -File | Where-Object CreationTime -lt  (Get-Date).AddDays(-365)  | Remove-Item -Force

Be the first to comment

Leave a Reply

Your email address will not be published.


*