您的位置:首页 > 理论基础

清理可能废弃的AD用户和计算机账户

2011-04-23 16:22 465 查看
#查找N天未活动的计算机或者用户,并移动到指定OU

#system.directoryservices.directorysearcher

#http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx

$maxOldLogonDays = 30

$TargetOU="OU=Computers,OU=Recycl_Bin,DC=TigerCompanyoa,DC=cn"

#$TargetOU="OU=users,OU=Recycl_Bin,DC=TigerCompanyoa,DC=cn"

$CSVFileLocation='C:\TEMP\OldObjects.CSV'

$query = New-Object system.directoryservices.directorysearcher

$root = [adsi]"LDAP://DC=TigerCompanyoa,DC=cn"

$query.SearchRoot = $root

$query.filter = "(objectCategory=computer)"

#$query.filter = "(objectCategory=user)"

$query.SearchScope = "subtree"

$query.PageSize = 100; #很奇怪,居然找到了近1万个计算机。。

$result = $query.findAll() |

ForEach-Object -process `

{

if ($_.properties.item("lastLogonTimestamp") -gt 0)

#I get alot of lastLogonTimestamps that are not null but not empty either

#-gt 0 seems to work best as test for valid datestamp

{

$rawLogon = $_.properties.item("lastLogonTimestamp")

$convertedLogOn = [datetime]::FromFileTime([int64]::Parse($rawLogon))

#To translate the lastLogonTimestamp attribute, we can use the FromFileTime static

#method from the system.datetime class. We also use the static method parse

#from the system.int64 class and give it the value we stored in the $rawLogon variable.

#We save the converted datetime object into the $convertedLogOn variable.

#Write-Host $convertedLogOn

$passwordage = ((get-date) - $convertedLogOn)

#Write-Host $passwordage.Days

If($passwordage.Days -gt $maxOldLogonDays)

{

#Write-Host "$($_.properties.item('distinguishedName'))

#has not logged on for more than $maxOldLogonDays days"

$($_.properties.item('distinguishedName')) | out-file $CSVFileLocation -Append #输出原来的DN

#Move-ADObject -Identity "$($_.properties.item('distinguishedName'))" -TargetPath $TargetOU #移动到指定OU

}

}

}

本文出自 “两只老虎” 博客,转载请与作者联系!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: