Een simpel script om gebruikers na x aantal dagen niet aanmelden automatisch te laten blokkeren. Daarbij een switch voor het dry-runnen van dit script om de implicaties in te schatten en natuurlijk een logging optie. Sla het onderstaande op als DisableUsersAfterInactiveDays.ps1
param(
[string]$OU = "OU=Users,DC=domain,DC=com", # Specify the target OU
[int]$InactiveDays = 30, # Number of days of inactivity
[switch]$DryRun = $false, # Dry run mode switch
[string]$LogFilePath # Optional log file path
)
# Function to log messages if logging is enabled or output to console if no log file path is provided
function LogMessage {
param(
[string]$message
)
if ($LogFilePath) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "$timestamp - $message"
Add-content -Path $LogFilePath -Value $logEntry
} else {
Write-Output $message # Output to console if no log file path provided
}
}
# Get the current date
$currentDate = Get-Date
# Retrieve inactive users in the specified OU
$inactiveUsers = Get-ADUser -Filter {Enabled -eq $true} -SearchBase "$OU" -Properties LastLogonDate |
Where-Object {($_.LastLogonDate -lt ($currentDate).AddDays(-$InactiveDays)) -or (-not $_.LastLogonDate)}
# Process inactive users
foreach ($user in $inactiveUsers) {
$userName = $user.Name
$lastLogon = $user.LastLogonDate
if ($DryRun) {
LogMessage "Dry run: User $userName would be disabled. Last logon: $lastLogon"
} else {
Disable-ADAccount -Identity $user
LogMessage "User $userName disabled. Last logon: $lastLogon"
}
}
Voorbeeld met output naar scherm:
.\DisableUsersAfterInactiveDays.ps1 -OU "OU=Sales,DC=contoso,DC=com" -InactiveDays 45 -DryRun
Voorbeeld met output naar logfile:
.\DisableUsersAfterInactiveDays.ps1 -OU "OU=Sales,DC=contoso,DC=com" -InactiveDays 45 -DryRun -Logfilepath "C:\beheer\DisableUsersAfterInactiveDays.txt"
De definitieve taak zonder -dryrun kun je vervolgens schedulen:
.\DisableUsersAfterInactiveDays.ps1 -OU "OU=Sales,DC=contoso,DC=com" -InactiveDays 45 -Logfilepath "C:\beheer\DisableUsersAfterInactiveDays.txt"
Wil je een overzicht van inactieve domain computers?
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 180 | select name
Om dit tot een verwijder actie om te zetten(draai altijd de vorige variant eerst!):
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan (New-TimeSpan -Days 90) | ForEach-Object { Remove-ADComputer -Identity $_.DistinguishedName -Confirm:$false }