StaleHosts.psm1
<#
.Synopsis This module can be used to find stale objects in Active Directory, such as inactive computer or user accounts and empty security groups. By default, this script will search for objects that have been inactive for a year (365 days). Reports are output as HTML tables to $home\Desktop Written by vasken@ucr.edu .Description Get-StaleHosts is a wrapper around the search-adaccount,get-adgroup, and get-aduser cmdlets. 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 .Example Get-StaleHosts -ADObjectType Group #> function Get-StaleHosts { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateSet('User','Computer', 'Group')] [string[]]$ADDObjectType = "Computer", [ValidateLength(1,3)] [String]$TimeFrame = "365", [Switch]$ErrorLog, [String]$LogFile ='$home\Desktop\Get-StaleHosts_errors.txt' ) begin { switch ($ADDObjectType) { "Computer" {Get-StaleComps($TimeFrame)} "User" {Get-StaleUsers($TimeFrame)} "Group" {Get-EmptyADGroups} default {exit} } } process{} end{} } $h = "<style>" $h = $h + "BODY{background-color:white;}" $h = $h + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}" $h = $h + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:coral;}" $h = $h + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:bisque;}" $h = $h + "</style>" function Get-StaleComps { ${stale comps} = $(Search-ADAccount -accountinactive -computersonly -timespan $args[0] | Sort-Object lastlogondate) $x = foreach ($e in ${stale comps}) { $e | Select-Object -Property LastLogonDate,Name,Enabled } $x | ConvertTo-Html -head $h | Out-File $home\Desktop\Stale_Comps.html } function Get-StaleUsers { $d = (Get-Date).Adddays(-($args[0])) ${stale users} = Get-ADUser -Filter {LastLogonTimeStamp -lt $d -and enabled -eq $true} -Properties LastLogonTimeStamp $x = foreach ($e in ${stale users}) { $e | Select-Object -Property Name,GivenName, @{Name="Surname";Expression={([DateTime]::FromFiletime([Int64]::Parse($_.LastLogonTimestamp)))}} } $x | ConvertTo-Html -head $h | Out-File $home\Desktop\Stale_Users.html } function Get-EmptyADGroups { Get-ADGroup -filter * | where {-Not ($_ | Get-ADGroupMember -ErrorAction SilentlyContinue )}| Select Name | ConvertTo-Html -head $h | Out-File $home\Desktop\Empty_Groups.html } Export-ModuleMember -function Get-StaleHosts |