private/Get-InactiveComputers.ps1
function Get-InactiveComputers { <# .SYNOPSIS This function gets Computers in the domain that have been inactivate (not logged on) for $DaysInactive Optionally specify the $Disable to disable the account and move them to the _DISABLED OU .NOTES Name: Get-InactivateComputers Author: Elliott Marter .EXAMPLE Get-InactivateComputers -DaysInactive 90 -DisableAccount .LINK https://www.powershellgallery.com/profiles/elliottmarter #> [cmdletbinding(SupportsShouldProcess=$True)] Param( [Parameter(Mandatory)] [int] $DaysInactive, [switch] $DisableAccount ) $Date = (Get-Date -UFormat %Y-%m-%d) Start-Transcript -OutputDirectory "C:\elm_adtools_logs\$Date" $domain = (Get-ADDomain).DistinguishedName $oucheckname = "_DISABLED" $oucheck = [adsi]::Exists("LDAP://OU=$oucheckname,$domain") if ($oucheck -eq $false) { New-ADOrganizationalUnit -Name _DISABLED } $DisabledOU = (Get-ADOrganizationalUnit -Filter 'Name -eq "_DISABLED"').DistinguishedName $Computers = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan "$DaysInactive.00:00:00" | Where-Object { ($_.Enabled -eq $true) -and ($_.lastlogondate -ne $null)} $Computers | Sort-Object LastLogonDate | Select-Object Name,LastLogonDate if ($DisableAccount) { foreach ($C in $Computers) { $Description = (get-adcomputer -Identity $U.SamAccountName -Properties description).description $Note = " (Disabled: $(get-date -UFormat %d/%m/%y))" $NewDescription = $Description + $Note Set-ADcomputer -Identity $U.DistinguishedName -Description $NewDescription -Enabled $false Move-ADObject -Identity $U.DistinguishedName -TargetPath $DisabledOU Write-Verbose "Successfully disabled $($Item.Name)" } } } |