Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Last active March 14, 2021 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfroThundr3007730/6f807e6e28fd38936100bc6f9aefb2fa to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/6f807e6e28fd38936100bc6f9aefb2fa to your computer and use it in GitHub Desktop.
Archives roaming profiles for deleted accounts, then deletes expired archived profiles.
# Archives roaming profiles for deleted accounts, then
# deletes old archived profiles, after retention period.
Start-Transcript C:\ProgramData\profile-hygiene.log -Append
$homePath = '\\file\User_Home$'
$profilePath = '\\file\User_Profile$'
function Remove-UserDirectory ($archivePath) {
foreach ($dir in (Get-ChildItem $archivePath)) {
if ((Get-Item ($dir.FullName + '\stamp')).LastWriteTime -lt (Get-Date).AddDays(-60)) {
Write-Host 'Retention period expired for archived user directory:' $dir.FullName
Write-Host 'Deleting permanently.'
Remove-Item $dir.FullName -Recurse -Force
}
}
}
function Archive-UserDirectory ($directoryPath) {
$archivePath = $directoryPath + '\.archive'
foreach ($dir in (Get-ChildItem $directoryPath -Exclude .archive)) {
if (!(Get-ADUser -Filter { SamAccountName -eq $dir.Name })) {
Write-Host 'No user account found in AD for user directory:' $dir.FullName
Write-Host 'Archiving directory.'
# Shouldn't be possible, but nuke the duplicate if it exists
if (Test-Path ($archivePath, $dir -join '\')) {
Write-Host 'Removing duplicate archive directory.'
Remove-Item ($archivePath, $dir -join '\') -Recurse -Force
}
$dir = Move-Item $dir $archivePath -Force -PassThru
[void](New-Item ($dir.FullName + '\stamp'))
}
}
}
Write-Host 'Cleaning up old user home directories.'
Archive-UserDirectory $homePath
Remove-UserDirectory ($homePath + '\.archive')
Write-Host 'Cleaning up old user profile directories.'
Archive-UserDirectory $profilePath
Remove-UserDirectory ($profilePath + '\.archive')
Write-Host 'Cleanup of old user directories complete.'
Stop-Transcript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment