StaleHosts.psm1
<#
.Synopsis This module can be used to find stale objects and users in Active Directory. By default, this script will search for objects that have been inactive for a year (365 days). Written by vasken@ucr.edu .Description Get-StaleHosts is a wrapper around the search-adaccount cmdlet. It will print users and/or computers that have not logged in for a specified time (defined by the TimeFrame parameter .Parameter ADObjectType This mandatory parameter represents the Active Directory object type to search for. It must be either 'Computer' or 'User' .Parameter TimeFrame This optional parameter represents the number of days the account has been inactive for, and must be an integer between 1 and 999. .Example Get-StaleHosts -ADObjectType Computer .Example Get-StaleHosts -ADObjectType Computer -TimeFrame 45 .Example Get-StaleHosts -ADObjectType User .Example Get-StaleHosts -ADObjectType User -TimeFrame 700 #> function Get-StaleHosts { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateSet('User','Computer')] [string[]]$ADObjectType = "Computer", [ValidateLength(1,3)] [String]$TimeFrame = "365", [Switch]$ErrorLog, [String]$LogFile ='c:\Get-StaleHosts_errors.txt' ) begin { switch ($ADObjectType) { "Computer" {Get-StaleComps($TimeFrame)} "User" {Get-StaleUsers($TimeFrame)} default {exit} } } process{} end{} } function Get-StaleComps { ${stale comps} = $(search-adaccount -accountinactive -computersonly -timespan $args[0] | Sort-Object lastlogondate) foreach ($e in ${stale comps}) { Write-Host -foregroundcolor white -backgroundcolor darkcyan -nonewline "Last login: " $e.LastLogonDate" " Write-Host -foregroundcolor white -backgroundcolor blue -nonewline " "$e.name" " if($e.Enabled -eq $false) { Write-Host -foregroundcolor white -backgroundcolor red " Disabled " } else { Write-Host -foregroundcolor white -backgroundcolor darkcyan " Enabled " } } } function Get-StaleUsers { $x = (Get-Date).Adddays(-($args[0])) ${stale users} = Get-ADUser -Filter {LastLogonTimeStamp -lt $x -and enabled -eq $true} -Properties LastLogonTimeStamp foreach ($y in ${stale users}) { Write-Host -foregroundcolor white -backgroundcolor darkcyan -nonewline "Last login: " ([DateTime]::FromFiletime([Int64]::Parse($y.LastLogonTimestamp)))" " Write-Host -foregroundcolor white -backgroundcolor blue -nonewline " "$y.givenname" " Write-Host -foregroundcolor white -backgroundcolor darkcyan " "$y.name" " } } |