Get AD Computer examples

get computer

In this post, I want to share a few examples of Get-ADComputer command. If ever you wondered how to get computer objects from Active Directory by some specific property, by password last set property or range, last logon date, or some other search criteria this article if for you. Below you can find few scripts that I was using recently ūüôā

Get all computers

To get all computers from Active Directory we can just run the following one-liner command:

Get-ADComputer -Filter *

There are multiple parameters that can be used in this command like SearchBase where you can specify Organizational Unit. For more basic examples you can refer to the Microsoft Docs page.

Get-ADComputer -Filter * -SearchBase 'OU=Computers,DC=powershellbros,DC=com' 

This more advanced script will get all computers and also export results to CSV file:

#===============================================================================================
# -------------------------------- PARAMS and MODULE -------------------------------------------
#=============================================================================================== 
Try{
    # Import Modules
    Import-Module ActiveDirectory -ErrorAction Stop
    
    # Params
    $RunTime     = (Get-Date).ToUniversalTime()
    $SavePath    = "$PSScriptRoot\Reports"
    $DCName      = ($env:LOGONSERVER -replace "\\",'')
    $FileDate    = Get-Date -Format "yyyyMMddHHmmss"
    $OutputCsv   = "$SavePath\$($FileDate)_All_Computers.csv"  
    $Folder      = Test-Path $SavePath; if (-not $Folder) { [void] (New-Item $SavePath -Type Directory -ErrorAction Stop) }

    "::::::: Script start time: $RunTime"
    "`nGetting all computes"
    "Results will be saved in: $OutputCsv"
    "Please wait...."
}
Catch{
    Write-Warning $_.Exception.Message
    Read-Host "Script will end. Press enter to close the window"
    Exit
}


#===============================================================================================
# ---------------------------------- GET COMPUTERS ---------------------------------------------
#=============================================================================================== 
# Properties 
 $Props = @{
        Filter         = "*"
        Server         = $DCName
        ResultPageSize = 5000000
        ResultSetSize  = $null
        Properties     = 'Name',  
                         'DistinguishedName', 
                         'LastLogonDate',
                         'OperatingSystem', 
                         'OperatingSystemVersion', 
                         'whenCreated'
}

# Get computers and export to CSV
Get-ADComputer @Props | foreach {
        New-Object PSObject -Property ([ordered]@{ 
  
                        'Computername'             = $_.name
                        'DistinguishedName'        = $_.DistinguishedName
                        'OS information'           = If($_.OperatingSystem){$_.OperatingSystem}Else{" - "}
                        'OS version information'   = If($_.OperatingSystemVersion){$_.OperatingSystemVersion}Else{" - "}
                        'Last Logon Date'          = $_.LastLogonDate
                        'When Created'             = $_.WhenCreated
                   
        }) | Export-Csv $OutputCsv -NoTypeInformation -Append     
} 


#===============================================================================================
# --------------------------------- FINAL RESULTS ----------------------------------------------
#=============================================================================================== 
# End time
$EndTime = (Get-Date).ToUniversalTime()
"::::::: Script end time: $EndTime"
$up      = $EndTime - $RunTime
$uptime  = "$($up.Days) days, $($up.Hours)h, $($up.Minutes)mins"

 # Results
"`nScript was running for: $uptime"
"Total number of computers: $((Import-CSV $OutputCsv | Measure-Object).COUNT)"

Read-Host "Press enter to close"


Get computer by lastlogondate property

Next example can be useful to find computers where lastlogondate is greater than 30 days. LDAPFilter: “(&(objectclass=computer)(lastlogontimestamp<=$LastLogon))”

# Params ##################################################################
$LastLogon   = (Get-Date).AddDays(-30).ToFileTime()
$Props = @{
        LDAPFilter     = "(&amp;(objectclass=computer)(lastlogontimestamp<=$LastLogon))"
        Server         = ($env:LOGONSERVER -replace "\\",'')
        ResultPageSize = 2000
        ResultSetSize  = $null
        Properties     = 'Name', 
                         'OperatingSystem', 
                         'SamAccountName', 
                         'DistinguishedName', 
                         'LastLogonDate'
}
  
# Get computers
Get-ADComputer @Props | select $Props.properties

Get computer by pwdlastset property

Here is a similar situation but this time it will get enabled comptuer objects by pwdlastset property. LDAPFilter: “(&(objectclass=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(pwdlastset<=$pwd))”

#Import Modules and provide range ############################################        
Try{
    Import-Module ActiveDirectory -ErrorAction Stop
    [int]$Start = Read-Host "Please provide number for Password Last Set days (for example greater than 30 days ago)"
}
Catch{
    Write-Warning $_.Exception.Message
    Read-Host "Script will end. Press enter to close the window"
    Exit
}


#Params ##################################################################
$pwd       = (Get-Date).AddDays(-$($Start)).ToFileTime() 
$FileDate  = Get-Date -Format "yyyyMMddHHmmss"
$OutputCsv = "$PSScriptRoot\Reports\$($FileDate)_PwdLastSet_Computers_$($Start)_days.csv"
  
"`nResults will be saved $OutputCsv"
"Generating report. Please wait..."

#Properties ############################################################## 
$Props = @{
    LDAPFilter     = "(&amp;(objectclass=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(pwdlastset<=$pwd))"
    Server         = ($env:LOGONSERVER -replace "\\",'')
    ResultPageSize = 2000000
    ResultSetSize  = $null
    Properties     = 'DistinguishedName','OperatingSystem', 'LastLogonDate' ,'pwdlastset', 'PasswordLastSet'
 }
 
Get-ADComputer @Props | FOREACH {
                
    New-Object PSObject -Property ([ordered]@{ 
  
        Computername         = $_.name
        Enabled              = $_.enabled
        DistinguishedName    = $_.DistinguishedName
        OrganizationalUnit   = If($_.DistinguishedName){(($_.DistinguishedName -split '\,')[1]).trim()}Else{' - '}
        OperatingSystem      = $_.OperatingSystem
        LastLogonDate        = $_.LastLogonDate
        PasswordLastSet      = If($_.PasswordLastSet){$_.PasswordLastSet}Else{' - '}
        PasswordLastSetDiff  = If($_.PasswordLastSet){(New-TimeSpan $_.PasswordLastSet) | %{"$($_.Days) days, $($_.Hours)h, $($_.Minutes)mins"}}Else{' - '}

                   
    })
            
} | Export-Csv $OutputCsv -NoTypeInformation -Append
            
"$((Import-CSV $OutputCsv | Measure-Object ).count) computers with password last set greater than $Start days"

Read-Host "Press enter to close"

Get computer by password last set date range

In this example, you can find how to get computers by password last set date range. You will be asked to provide time range and script will get objects using LDAPfilter “(&(objectclass=computer)(pwdlastset<=$PwdStart)(pwdlastset>=$PwdEnd))”:

#===============================================================================================
# -------------------------------- PARAMS and MODULE -------------------------------------------
#=============================================================================================== 
Try{
    # Import Modules
    Import-Module ActiveDirectory -ErrorAction Stop
    
    # Specify range            
    [int]$Start = Read-Host "Please provide number for start of the range like 80 (80-90 days)"
    [int]$End   = Read-Host "Please provide number for end of the range like 90 (80-90 days)"
}
Catch{
    Write-Warning $_.Exception.Message
    Read-Host "Script will end. Press enter to close the window"
    Exit
}

# Proceed if range is valid
If($End -lt $Start){
    Write-Warning "End of the time range is greater than start"
    Exit
}


#===============================================================================================
# ---------------------------------- GET COMPUTERS ---------------------------------------------
#=============================================================================================== 
Try{
    # Params
    $PwdEnd    = (Get-Date).AddDays(-$($End)).ToFileTime() 
    $PwdStart  = (Get-Date).AddDays(-$($Start)).ToFileTime() 
    $FileDate  = Get-Date -Format "yyyyMMddHHmmss"
    $SavePath  = "$PSScriptRoot\Reports"
    $OutputCsv = "$SavePath\$($FileDate)_PwdLastSet_Computers_($($Start)-$($End)).csv"
    $Folder    = Test-Path $SavePath; if (-not $Folder) { [void] (New-Item $SavePath -Type Directory -ErrorAction Stop) }

    "`nResults will be saved $OutputCsv"
    "Generating report. Please wait..."

    # Command params
    $Props = @{
                LDAPFilter     = "(&amp;(objectclass=computer)(pwdlastset<=$PwdStart)(pwdlastset>=$PwdEnd))"
                Server         = ($env:LOGONSERVER -replace "\\",'')
                ResultPageSize = 2000000
                ResultSetSize  = $null
                Properties     = 'DistinguishedName',
                                 'OperatingSystem', 
                                 'LastLogonDate',
                                 'pwdlastset', 
                                 'PasswordLastSet'
    }
 
    # Get computers
    $Comps = Get-ADComputer @Props | Select-Object 'Name', 
                                                   'Enabled', 
                                                   'DistinguishedName', 
                                                   'OperatingSystem', 
                                                   'LastLogonDate',
                                                   'PasswordLastSet', 
                                                   @{n='PasswordLastSetDiff';e={(New-TimeSpan $_.PasswordLastSet) | %{"$($_.Days) days, $($_.Hours)h, $($_.Minutes)mins"}}} 
}
Catch{
    Write-Warning $_.Exception.Message
    Read-Host "Script will end. Press enter to close the window"
    Exit
}


#===============================================================================================
# ---------------------------------- FINAL RESULTS ---------------------------------------------
#===============================================================================================        
 If($Comps){
    # Count computers
    $CompCount = ($Comps | Measure-Object).count
    "$CompCount computers"

    # Export results
    $Comps | Export-Csv $OutputCsv -NoTypeInformation -Force
}
Else{
    "No results for ($($Start)-$($End)) time range" 
}

Read-Host "Press any key to close"

Get computer by any property

In last example, you can specify any property and value in LDAP filter: “(&(objectclass=computer)($Property=$Value))”


#Import Modules and provide property ############################################        
Try{
    Import-Module ActiveDirectory -ErrorAction Stop
                
    [string]$Property = Read-Host "Please provide computer property name, for example OperatingSystem"
    [string]$Value    = Read-Host "Please provide $Property property value, for example Windows 10 Enterprise"
}
Catch{
    Write-Warning $_.Exception.Message
    Read-Host "Script will end. Press enter to close the window"
    Exit
}

If(!$Property -and !$Value){
    Write-Warning "Something went wrong"
}
Else{
    #Params ##################################################################
    $FileDate  = Get-Date -Format "yyyyMMddHHmmss"
    $OutputCsv = "$PSScriptRoot\Reports\$($FileDate)_$($Property).csv"
  
    "`nResults will be saved $OutputCsv"
    "Generating report. Please wait..."

    #Properties ############################################################## 
    $Props = @{
            LDAPFilter     = "(&amp;(objectclass=computer)($Property=$Value))"
            Server         = ($env:LOGONSERVER -replace "\\",'')
            ResultPageSize = 2000000
            ResultSetSize  = $null
            Properties     = "$($Property)"
    }
 
    $Comps = Get-ADComputer @Props | select 'Name', 'Enabled', $Property
        
    If($Comps){
        $CompCount = ($Comps | Measure-Object).count
        "$CompCount computers"
        $Comps | Export-Csv $OutputCsv -NoTypeInformation -Force
    }
    Else{
        "No results for $Property" 
    }
}
Read-Host "Press any key to close"

       

Please note ūüôā that WordPress is adding &amp; characters to LDAPFilter: “(&amp;(objectclass=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(pwdlastset<=$pwd))”.

Valid LDAPFilter:

I hope this was informative for you ūüôā See you in next articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.