Files
DeleteOldProfiles/scripts/DeleteOldProfilesNetProfile.ps1
2025-02-10 13:02:54 -06:00

39 lines
1.4 KiB
PowerShell

# Delete old profiles based off of the last login in AD
$daysInactive = 14 # Specify the number of days of inactivity
$homeDirectoryPath = "C:\Users" # Path to user home directories
$domainName = "local" # Domain name that the pc is on
$excludedProfiles = @("Default User", "administrator")
$inactiveDate = (Get-Date).AddDays(-$daysInactive)
$profiles = Get-WmiObject Win32_UserProfile
# Get all user profiles
:Loop foreach ($profile in $profiles) {
$userFolder = $profile.LocalPath
$userName = $profile.LocalPath.Split('\')[-1] # Get the username from the folder path
$nameIsExcluded = $false
foreach ($name in $excludedProfiles) {
if ($item -eq $userName) {
continue Loop
}
}
# Get the last logon time for the local user
$userLogon = Get-WmiObject -Class Win32_NetworkLoginProfile -Filter "Name='$domainName\\$userName'" | Select-Object -Property LastLogon
if ($userLogon) {
$lastLogonDate = [Management.ManagementDateTimeConverter]::ToDateTime($userLogon.LastLogon)
# Check if the user's last local logon date is older than the specified inactive date
if ($lastLogonDate -lt $inactiveDate) {
Write-Host "Deleting user profile: $($profile.LocalPath) Last Logon: $lastLogonDate" -ForegroundColor Red
# Remove the user profile
$profile.Delete()
}
}
}