Post

Finding and Cleaning Unused Computers in Active Directory

PS:

Import-Module activedirectory

# Parametreler girelim.

$domain = “guler.com”

$DaysInactive = 180

$time = (Get-Date).Adddays(-($DaysInactive))

$date = Get-Date ($time) -UFormat %d.%m.%y

$File = “c:\Inactive_Computers.csv”

# Son 180 günde oturum açılmamış bilgisayarları $file yolundaki dosyaya listeler

$CompList = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time -and operatingSystem -notlike “*server*”} -SearchBase “DC=guler, DC=com” -Properties Name,LastLogonTimeStamp,OperatingSystem |

Select-Object Name, OperatingSystem, @{Name=”Last Logon TimeStamp”; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | Export-Csv $File -encoding UTF8 -notypeinformation

# Son 180 günde oturum açılmamış bilgisayarların isimlerini toplar

$Computers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time -and operatingSystem -notlike “*server*”} -SearchBase “DC=guler, DC=com” -Properties Name,LastLogonTimeStamp,OperatingSystem |

Select-Object -ExpandProperty Name

# Toplanan bilgisayarları domainden siler. Silinenleri ve silinmeyenleri loglar

ForEach ($Computer in $Computers)

{   Try {

        Remove-ADComputer -Identity $Computer -ErrorAction Stop -confirm:$false

        Add-Content C:\removed-computers.log -Value “$Computer silindi”

    }

    Catch {

        Add-Content C:\not-removed-computers.log -Value “$Computer bulunamadi $($Error[0])”

    }

}

Faydalı olması dileğiyle. – Hope it’s useful.

This post is licensed under CC BY 4.0 by the author.