从活动目录创建已删除用户的CSV文件

时间:2014-04-14 03:35:24

标签: powershell csv active-directory

获得以下代码,我可以创建用户的CSV文件,但希望它仅由将从其上方的循环中删除的用户填充。只是没有看到如何将两者结合在一起。 基本上,它会将所有将被删除的用户拉到90天以上,然后将用户信息输入CSV。

$OU='OU=Users,OU=Test,DC=corporate,DC=domain,DC=com'

$LISTOFACCOUNTS=Get-ADUser -Property lastlogondate -SearchBase $OU -Filter {lastLogonDate -lt $NumberDays}

$LISTOFACCOUNTS | DISABLE-ADACCOUNT -WhatIf

$LISTOFPOTENTIALDELETES=Get-ADUser -SearchBase $OU -Property Lastlogondate -Filter` {lastlogondate -lt $DeleteDate}

FOREACH ($USER in $LISTOFPOTENTIALDELETES) { 

    IF (($USER.Notes -notlike '*'+$OVERRIDE+'*') -and ($USER.Description -notlike` '*'+$OnLeave+'*')) 
    { 
        WRITE-HOST $USER.SamAccountName 'Deleted' 
        REMOVE-ADOBJECT $USER.SamAccountName -whatif 
    } 
    ELSEIF ($USER.Notes -like '*'+$OVERRIDE+'*') 
        { 
            WRITE-HOST $USER.SamAccountName 'Not removed due to Administrative Override'  
         } 
        ELSE 
        { 
            WRITE-HOST $USER.SamAccountName 'Not removed - Presently on Leave' 
        } 
} 

$memberOf = @{n='MemberOf';e={ ($_.MemberOf -replace '^CN=([^,]+).+$','$1') -join ';' }}
$LastLogonDays = @{N='Last Logon Days'; E={$($(Get-Date) - ` $([DateTime]::FromFileTime($_.LastLogon))).Days}}
$LastLogon = @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}}
$Mail =  @{ Name = 'mail'; Expression = { $_.mail -join ';'; }; }
$Description = @{N='Description'; E={$_.description -join ';'; }; }

Get-ADUser -Filter * -SearchBase $OU -Properties * | Select Enabled, SAMAccountName, ` CanonicalName, Displayname,Givenname, Surname, Department, `
ProfilePath, HomeDrive, $Description,  $LastLogonDays, $LastLogon, $mail, $memberOf | 
Export-CSV "E:\Temp\_DisabledUserList.csv"

提前干杯

1 个答案:

答案 0 :(得分:0)

在用户对象被删除之前构建一个列表:

$deletedUsers = @()
foreach ($USER in $LISTOFPOTENTIALDELETES) {
  if ($USER.Notes -notlike ...) { 
    Write-Host $USER.SamAccountName 'Deleted'
    $deletedUsers += $USER
    Remove-ADObject $USER.SamAccountName -WhatIf 
  } else {
    ...
  }
}

并将该列表导出为CSV:

$deletedUsers | select SamAccountName, ... | Export-Csv 'C:\Temp\deleted.csv'

附注:我建议使用Remove-ADUser代替Remove-ADObject来移除AD用户。