I’m guessing i need a -Exclude but i’m unsure of where it goes and how to exactly implement it.
##Check bottom of script for setting specific OU
Function Get-LastLogon {
param(
[string]$OUName
)
# Get all matching OUs on any level
$OUs = Get-ADOrganizationalUnit -Filter "Name -like '$OUName'"
$DCs = Get-ADDomainController -Filter *
# Get all users from each OU from each DC
$ADUsers = Foreach ($OU in $OUs) {
Foreach ($DC in $DCs.HostName) {
Get-ADUser -SearchBase $OU.DistinguishedName -Filter * -Properties LastLogon -server $dc |
Select-Object Name,@{N='userPrincipalName';E={$_.userPrincipalName.Split("_")[0]}}, @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}
}
}
# return most recent LastLogon date for each user
$ADUsers |
Group Name,userPrincipalName |
Select Name,@{N='userprinciplename';E={$_.userprinciplename.Split("_")[0]}}, @{n='LastLogon';e={$_.Group.LastLogon | sort -desc | select -First 1}}
} ## End function
$OUcustom = Read-Host -prompt 'Enter OU here or "Clients" for all'
##Enter the OU here
Get-LastLogon -OUName $OUcustom |
##export csv
Export-Csv -path "C:\temp\UserExport_$((Get-Date).ToString("ddMM_HHmm")).csv" -NoTypeInformation
".csv extracted to C:\temp"
pause
I’d urgently recommend to do a big step back and take your time and start with learning the very basics of PowerShell first. That will save you from a lot of wasted time and frustrations.
The results didn’t output any numbers no…
Even when i just ran what you have here though and just adding in $OUName = ‘Clients’ it didn’t output any numbers.
I also tried Where-Object -Property 'Name' -NotMatch -Value 'zzOldUsers'
and Where-Object -Property 'DistinguishedName' -Notlike -Value '*zzOldUsers*'
and these just printed the code out, no numbers.
Double checked the OU is zzOldUsers with the “s” on the end too, so it’s not that throwing the code off.
Under the Clients folder.
In AD we have the domain, then in that there is a “Clients” folder, then inside that there are folders for each client, and also the zzOldUsers folder.
The Dname of that folder is “OU=zzOldUsers,OU=Clients,DC=Company,DC=co,DC=uk” so i agree it is weird why it isn’t returning all the folders listed under the “Clients” folder.