#查找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
}
}
}