Get-ADComputerLastLogon

Finding old computers in Active Directory can be a bit difficult at times, but it’s a necessary evil. I threw together a small PowerShell script to assist in the search. You’ll also find some examples of how it can be used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function Get-ADComputerLastLogon {
[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string] $OU
    )
 
# Query AD
Write-Verbose "Querying OU $OU"
$ADQueryComputers = Get-ADComputer -Filter * -SearchBase $OU -Properties Name, lastLogonTimestamp, operatingSystem
 
$ADComputerFinal=@()
Foreach ($ADQueryComputer in $ADQueryComputers) {
 
    # Set Vars
    $ComputerName = $ADQueryComputer.Name
    $ComputerOS = $ADQueryComputer.operatingSystem
    $ComputerLastLogin = [datetime]::FromFileTimeUtc($ADQueryComputer.lastLogonTimestamp)
    $ComputerLastLoginTimeInDays = $(((Get-Date) - $ComputerLastLogin).Days)
 
    # Add to Final Var
    $ADComputer = [pscustomobject]@{
        Computer = $ComputerName
        OS = $ComputerOS
        LastLogonDays = [int]$ComputerLastLoginTimeInDays
    }
 
    $ADComputerFinal += $ADComputer
}
$ADComputerFinal
}

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Set OU
$OU = "OU=Laptops,OU=Computers,OU=Company,DC=lab,DC=local"            
 
# Just list all computers and last logon time in $OU
Get-ADComputerLastLogon -OU $OU
 
# Get computer last logon time if it's more then 100 days.
Get-ADComputerLastLogon -OU $OU | Where-Object LastLogonDays -gt 100
 
# Get computer last logon time if it's less then 50 days.
Get-ADComputerLastLogon -OU $OU | Where-Object LastLogonDays -lt 50
 
# Get specific computer
Get-ADComputerLastLogon -OU $OU | Where-Object Computer -match "LAB-SRV001"
 
# Get all computers running Windows Enterprise Edition if last logon time is less then 100 days
Get-ADComputerLastLogon -OU $OU | Where-Object { $_.OS -Match "Enterprise" -AND $_.LastLogonDays -lt "100" }
 
# count all the computers that have not signed in on the last 100 days
(Get-ADComputerLastLogon -OU $OU | Where-Object LastLogonDays -gt 100).Count
This entry was posted in Powershell. Bookmark the permalink.

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *

*


× två = 4

24 279 Spam Comments Blocked so far by Spam Free Wordpress

Följande HTML-taggar och attribut är tillåtna: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>