使用 Powershell 脚本删除 AD 用户及其关联文件夹

使用 Powershell 脚本删除 AD 用户及其关联文件夹

是否可以删除 AD 用户及其关联文件夹?文件夹结构如下:

D:\Users\Profiles
D:\Users\Redirect
D:\Users\Data

我正在尝试使用以下脚本删除 90 天内未登录的用户。这是不是我想要的是。

function Delete-ADUser
{
    Param($userName = $(throw 'Enter a username to delete'))
    $searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"","(&(objectcategory=user)(sAMAccountName=$userName))")
    $user = $searcher.findone().GetDirectoryEntry()
    $user.psbase.DeleteTree()
}


$NumDays = 90
$LogDir = ".\Removed-User-Accounts.log"

$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"
$users = $objstalesearcher.findone()

Write-Output `n`n"----------------------------------------" "ACCOUNTS OLDER THAN "$NumDays" DAYS" "PROCESSED ON:" $currentDate "----------------------------------------" `
| Out-File $LogDir -append

if ($users.Count -eq 0)
{
       Write-Output "  No account needs to be removed." | Out-File $LogDir -append
}
else
{
       foreach ($user in $users)
       {
              # Read the user properties
              [string]$adsPath = $user.Properties.adspath
              [string]$displayName = $user.Properties.displayname
              [string]$samAccountName = $user.Properties.samaccountname
              [string]$lastLogonInterval = $user.Properties.lastlogontimestamp

              # Delete the user
              Delete-ADUser $samAccountName

              # Convert the date and time to the local time zone
              $lastLogon = [System.DateTime]::FromFileTime($lastLogonInterval)

              Write-Output "  Removed user " $displayName" | Username: "$samAccountName" | Last Logon: "$lastLogon"`n" `
              | Out-File $LogDir -append
       }
}

问题:如何修改要求我输入用户名并删除其文件夹的脚本?

答案1

假设您在“addsServer”上运行此程序,因此 $profilePath 是机器本地的,并且 D:\Profiles\username 存储用户配置文件。

$GoodbyeList = 'JDoe', 'KDoe', 'LDoe'
$profilePath = 'D:\Profiles'

foreach ($user in $GoodbyeList) {
    Remove-ADUser -Identity $user
    Remove-Item "$profilePath\$user" -Recurse -Force -Verbose
}

答案2

如果您的用户不共享主目录的公共根位置,您可以在删除文件夹之前查询每个用户的主目录属性

foreach ($user 在 $GoodbyeList 中) { Remove-ADUser -Identity $user $homeDirectory = (Get-ADUser $user -Properties homeDirectory | Select-Object -ExpandProperty homeDirectory) Remove-Item "$homeDirectory" -Recurse -Force -Verbose }

相关内容