#查找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
$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
}
本文轉自 tigerkillu 51CTO部落格,原文連結:http://blog.51cto.com/chenyitai/551972,如需轉載請自行聯系原作者