通过powershell查询OU中被禁用的AD账号,并删除账户

function Invoke-RemoveADAccountGhost($User, $DomainController, $Time) {
    $ct = $User.whenCreated.ToString("yyyy-MM-dd HH:mm:ss")
    $lt = ""
    if ($User.LastLogonDate) {
        $lt = $User.LastLogonDate.ToString("yyyy-MM-dd HH:mm:ss")
    } else {
        $lt = "                   "
    }
    # if ($User.ProtectedFromAccidentalDeletion) {
    #     Set-ADObject -Identity $User -ProtectedFromAccidentalDeletion $false -Server $DomainController
    # }
    # Remove-ADUser -Identity $User -Confirm:$false -Server $DomainController
    return "${lt}|${ct}|$($User.Enabled)|$($User.SamAccountName)|$($User.DistinguishedName)|${DomainController}|$($User.Description)"
}
function Remove-ADAccountGhost {
    param (
        $DomainController,
        $FilePath
    )
    $Now = Get-Date
    $Time = $Now.ToString("yyyy-MM-dd HH:mm:ss")
    $180DaysAgo = $Now.AddDays(-90)
    $Users = @()
    $Res = New-Object System.Collections.ArrayList
    $OUS = Get-ADOrganizationalUnit -Filter { Name -like "*_Users_*" } -Server $DomainController
    for ($i = 0; $i -lt $OUS.Length; $i++) {
        $Users += Get-ADUser -SearchBase $OUS[$i].DistinguishedName -Filter { ( Enabled -eq $false -and lastLogonTimestamp -like "*" -and LastLogonDate -le $180DaysAgo ) -or ( lastLogonTimestamp -notlike "*" -and whenCreated -le $180DaysAgo -and Name -like "*(*" ) } -Server $DomainController -Properties LastLogonDate,whenCreated,ProtectedFromAccidentalDeletion,Description
    }
    for ($i = 0; $i -lt $Users.Length; $i++) {
        $null = $Res.Add($(Invoke-RemoveADAccountGhost -User $Users[$i] -DomainController $DomainController -Time $Time))
    }
    Out-File -FilePath $FilePath -Encoding utf8 -InputObject $Res -Append
}
$MAINSERVER = "VXIDCSH1.vxichina.com"
$APPLESERVER = "ACMDCSH1.apple.vxichina.com"
$FilePath = "ghostusers.txt"
Remove-ADAccountGhost -DomainController $MAINSERVER -FilePath $FilePath
Remove-ADAccountGhost -DomainController $APPLESERVER -FilePath $FilePath
posted @ 2022-06-09 21:33  XXLLA  阅读(187)  评论(0编辑  收藏  举报