How do I query Last Logon Date via Powershell - powershell

I'm trying to query machines which were last logged on to 30 days ago
Clear-Host
$Threshold = (Get-Date).AddDays(-30)
$NotInUse = Get-ADComputer -Filter * -Properties LastLogonDate | Where {
$_.name -Like "*LN-T48*" -and $_.LastLogonDate -gt $Threshold
}
$NotInUse | select Name, LastLogonDate -Verbose

Use -lt
Using the filter is quicker:
$Threshold = (Get-Date).AddDays(-30)
$NotInUse = Get-ADComputer -Filter {LastLogonDate -lt $Threshold} -Properties LastLogonDate |
Where { $_.name -Like "*LN-T48*"}
$NotInUse | select Name, LastLogonDate -Verbose | sort LastLogonDate

Related

How to get accountexpirationdate real date?

I would like to get the actual date of accounts that have expired but still enabled in the active directory. I always get the date + 1 day. For example, if a user is expired today (15/11/2022), it will shows (16/11/2022)... Can you help me with this?
Get-ADUser -Filter * -properties AccountExpirationDate |
Where-Object{$_.AccountExpirationDate -lt (Get-Date) -and $_.AccountExpirationDate -ne $null -and $_.Enabled -eq $True} |
select-object Name, SamAccountName, AccountExpirationDate | Sort-Object -Property {$_.AccountExpirationDate} -Descending
I always like to include LDAP property accountExpires in there (PowerShell conveniently converts this to local time in Property AccountExpirationDate)
to first check if the attribute has never been set (value 0) or if the attribute for the user has been set to 'Never Expires' (value 9223372036854775807).
Try
$refDate = (Get-Date).Date # set to midnight
# or use -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)"
Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |
Where-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and
($_.AccountExpirationDate -le $refDate)} |
Select-Object Name, SamAccountName, AccountExpirationDate |
Sort-Object AccountExpirationDate -Descending
Thanks Theo, ive found what i was looking for
Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |
Where-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and
($_.AccountExpirationDate -le $refDate)} |
Select-Object Name, SamAccountName, #{Name="AccountExpirationDate";Expression={(get-date $_.AccountExpirationDate).AddDays(-1)}} |
Sort-Object AccountExpirationDate -Descending

Powershell: Get all ADUsers from a list, with a specific E-Maildomain and has not logged in in 90 days

Im trying to write a script that goes through a CSV-File, searches up the Username in our AD and then gives me these users, that have a specific E-Maildomain and hasn't logged in for the last 90 days.
Here's what I got so far:
import-csv C:\pathtofile\user.csv | ForEach-Object {
Get-ADUser $_.SamAccountName -Filter "EMailAddress -like '*#thedomain.com'" -Properties SamAccountName,LastLogonDate | Where { ($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)} | Sort | Select Name,SamAccountName,LastLogonDate
}
But it gives me this weird error:
Get-ADUser : A positional parameter cannot be found that accepts argument 'Username'.
I tried to put the E-Mailsorting into my where-statement, but it was not able to find any users then...
Can you guys may see what I'm doing wrong?
Thank you for your help.
Kind regards,
Gabe
You cannot use parameter -Filter together with -Identity.
(using Get-ADUser $_.SamAccountName implicitely uses the -Identity parameter)
To filter out only users that are in your CSV file AND that have a specific domain in their email address, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Import-Csv -Path 'C:\pathtofile\user.csv' | ForEach-Object {
$userSam = $_.SamAccountName
try {
$user = Get-ADUser $userSam -Properties EmailAddress, LastLogonDate -ErrorAction Stop
if (($user.LastLogonDate) -and $user.LastLogonDate -lt $refDate -and
$user.EmailAddress -like '*#thedomain.com') {
$user | Select-Object Name,SamAccountName,EmailAddress,LastLogonDate
}
}
catch {
Write-Warning "User '$userSam' not found"
}
}
To filter out all users that have a specific domain in their email address, so not using the csv at all, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Get-ADUser -Filter "EmailAddress -like '*#thedomain.com'" -Properties EmailAddress, LastLogonDate |
Where-Object { ($_.LastLogonDate) -and $_.LastLogonDate -lt $refDate } |
Select-Object Name,SamAccountName,EmailAddress,LastLogonDate | Sort-Object Name
# show the result on screen
$result | Format-Table -AutoSize
# and/or save to a new csv file
$result | Export-Csv -Path 'C:\pathtofile\filteredusers.csv' -NoTypeInformation

Powershell last logon query. Help setting up array to go thought all my domain controllers

This script below works, but every attempt I make to have it cycle through all my domain controllers fail. How do I add a array to go through all these OUs on all my domain controllers. Thanks in advance!
$OUs= “OU=Test1,OU=Test1,OU=Test1,OU=Test1,OU=All Users,DC=domain,DC=local",
"OU=Test2,OU=Test2,OU=Test2,OU=All Users,OU=Test2,DC=domain,DC=local",
"OU=Test3,OU=Test3,OU=Test3,OU=All Users,OU=Test3,DC=domain,DC=local",
"OU=test4,OU=test4,OU=test4,OU=All Users,OU=test4,DC=domain,DC=local",
"OU=Test5,OU=test5,OU=Test5,OU=All Users,OU=test5,DC=domain,DC=local”
$OUs | ForEach-Object
{
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $_ -Properties Name,SamAccountName,LastLogonDate |
Where-Object {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)}
} |
Sort LastLogonDate |
Format-Table -Property Name,SamAccountName,LastLogonDate, DistinguishedName |
Out-String
Below you have now an array of your OUs. Please try whether that works for you now.
$OUs= #(
“OU=Test1,OU=Test1,OU=Test1,OU=Test1,OU=All Users,DC=domain,DC=local",
"OU=Test2,OU=Test2,OU=Test2,OU=All Users,OU=Test2,DC=domain,DC=local",
"OU=Test3,OU=Test3,OU=Test3,OU=All Users,OU=Test3,DC=domain,DC=local",
"OU=test4,OU=test4,OU=test4,OU=All Users,OU=test4,DC=domain,DC=local",
"OU=Test5,OU=test5,OU=Test5,OU=All Users,OU=test5,DC=domain,DC=local”
)
I would also suggest to break your line after every pipe in order to cut the line. That makes it far easier to read for you, plus your colleagues.
$OUs | ForEach-Object
{
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $_ -Properties Name,SamAccountName,LastLogonDate |
Where-Object {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)}
} |
Sort LastLogonDate |
Format-Table -Property Name,SamAccountName,LastLogonDate, DistinguishedName |
Out-String
You mention cycling through your domain controllers, but then you go on to ask about OUs. I suspect you want DC's, because each DC might have a different Last Logon Time for the user.
You can omit the -SearchBase and search all OU's, if you're looking to get this data for all users.
$Domains = Get-ADDomainController -Filter * #Note, this shows all DCs- you may have some without ADWS Installed, which won't handle the WHERE.
foreach ($domain in $Domains) {
Get-ADUser -Filter {Enabled -eq $TRUE} -Server $domain -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)} |
Export-CSV -Path 'UsersNotRecentlyLoggedIn.CSV' -Append
}
If you only want one DC, but all OUs
$Domains = Get-ADDomainController -Discover -Service ADWS
foreach ($domain in $Domains) {
Get-ADUser -Filter {Enabled -eq $TRUE} -Server $domain -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)} |
Export-CSV -Path 'UsersNotRecentlyLoggedIn.CSV' -Append
}

Select users from AD randomly

We've been tasked with creating a process to review random employee's web traffic on a quarterly basis. I have started a script in Powershell that selects 10 random users from a specific OU, but I'm still getting some unneeded data. I need help filtering down the list further. The output gives me users that have been disabled and left in the OU as well as PRN employees that haven't signed on in a long time. I would like to search AD accounts that has an email address & a logon, modified within the last 3 months. Here is an example of the code I have so far.
Get-ADUser -SearchBase "ou=ouname,ou=ouname,dc=domainname,dc=suffix" -Filter * | Select-Object -Property Name | Sort-Object{Get-Random} | select -First 10
[Edit: Question Answered]
Here is my final script, added $_.passwordlastset as a search attribute since this will pickup users that have changed their password in the last 90 days.
$DateFrom = (get-Date).AddDays(-90)
Get-ADUser -Properties * -Filter {enabled -eq $True} -SearchBase "ou=ouname,dc=domainname,dc=suffix" | where { $_.passwordlastset -gt $DateFrom -and $_.mail -ne $null } | Sort-Object {Get-Random} | select name, sAMAccountName -First 10
Get-ADUser -Properties name, mail, lastlogondate -Filter {enabled -eq $True} -SearchBase "ou=ouname,ou=ouname,dc=domainname,dc=suffix" | select name, mail, lastlogondate | where { $_.lastlogondate -gt (Get-Date).AddDays(-90) -and $_.mail -ne $null }
Here a start.
Try this:
$timeFrame = (get-Date).AddDays(-90)
get-aduser -SearchBase 'ou=ouname,ou=ouname,dc=domainname,dc=suffix' -Filter * -Properties * |
Where-Object {$_.whenChanged -gt $timeFrame -and $_.mail -ne $null} |
Select-Object -Property Name | Sort-Object{Get-Random} | select -First 10
Change the -Filter value:
# LastLogontimeStamp is not guaranteed to be updated on every login, so 30 days + 14 days margin
$threshold = (Get-Date).AddDays(-44).ToFileTime()
Get-ADUser -Filter {Enabled -eq $true -and LastLogontimeStamp -gt $threshold} -SearchBase "ou=ouname,ou=ouname,dc=domainname,dc=suffix" | Sort-Object {Get-Random} | Select Name -First 10
This filter will ensure that AD only returns Enabled users and that their lastLogontimeStamp value has been updated within the last month and a half
This will do everythign the OP stated:
$timeFrame = (get-Date).AddDays(-90)
get-aduser -SearchBase 'YourOU,DC=Domain,DC=com' -Filter * -Properties * |
Where-Object {$_.whenChanged -lt $timeFrame -and $_.mail -ne $null -and $_.Enabled -eq $true} |
Select-Object -Property Name | Sort-Object{Get-Random} | select -First 10
This should meet all the OPs checkpoints via the snippets:
"I would like to search AD accounts that has an email address"
$_.mail -ne $null
"& a logon"
$_.Enabled -eq $true
"modified within the last 3 months"
$_.whenChanged -lt $timeFrame

Search AD computer with window 7 only under entire active directory except one OU "disabled"

I am looking for script to search only Window 7 computer in AD with not login since 60 days. Exclude Quarantine OU, I am using this coded but it's not working:
Import-Module ActiveDirectory
$DaysInactive = 60
$time = (Get-Date).AddDays(-$DaysInactive)
# Get all AD computers with lastLogonTimestamp less than our time
Get-ADComputer -Filter { LastLogonTimeStamp -lt $time -and OperatingSystem -like 'Windows 7 *'} -Properties LastLogonTimeStamp |
Where-Object { $_.DistinguishedName -notlike '*,OU=COMPUTERS,OU=Quarantine,DC=ad,DC=int,DC=com,*' }
# Output hostname and lastLogonTimestamp into CSV
Select-Object Name, #{ Name = "Stamp"; Expression = { [DateTime]::FromFileTime($_.lastLogonTimestamp) } } |
Export-Csv OLD_Computer.csv -NoTypeInformation
You're just missing a pipe bind between the get and select, delete the comment and replace with a | like so:
Get-ADComputer -Filter { LastLogonTimeStamp -lt $time -and OperatingSystem -like 'Windows 7 *'} -Properties LastLogonTimeStamp | Where-Object { $_.DistinguishedName -notlike '*,OU=COMPUTERS,OU=Quarantine,DC=ad,DC=int,DC=com,*' } | Select-Object Name, #{ Name = "Stamp"; Expression = { [DateTime]::FromFileTime($_.lastLogonTimestamp) } } | Export-Csv OLD_Computer.csv -NoTypeInformation
This command executes fine in my environment.