Testing a code Powershell script to query domain of multiple criteria. Here’s my PowerShell script that queries a domain for computer objects that are 90 days old or more, and outputs the results to a CSV file. This script uses the Get-ADComputer cmdlet from the Active Directory module.
# Import the Active Directory module
Import-Module ActiveDirectory
# Get the date 90 days ago
$90DaysAgo = (Get-Date).AddDays(-90)
# Get all computer objects that haven't logged on for 90 days or more
$StaleComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $90DaysAgo} -Properties Name, LastLogonTimeStamp, OperatingSystem, Enabled, IPv4Address, PasswordLastSet
# Create an array to hold the output
$Output = @()
# Loop through each stale computer
foreach ($Computer in $StaleComputers) {
# Get the computer's last logon date
$LastLogonDate = [DateTime]::FromFileTime($Computer.LastLogonTimeStamp)
# Get the computer's password age
$PasswordAge = (Get-Date) - $Computer.PasswordLastSet
# Add the computer's information to the output
$Output += [PSCustomObject]@{
'Computer Name' = $Computer.Name
'Last Logon Date' = $LastLogonDate
'Operating System' = $Computer.OperatingSystem
'Enabled' = $Computer.Enabled
'IP Address' = $Computer.IPv4Address
'Password Age (Days)' = $PasswordAge.Days
}
}
# Export the output to a CSV file
$Output | Export-Csv -Path "Stale_Computers.csv" -NoTypeInformation
Still testing phases
New contributor
Gonzo2011 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.