Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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