0
votes

I am currently creating a PowerShell script to scan Active Directory for users who have not signed in in the last year.

Import-Module ActiveDirectory

$DaysInactive = 365
$InactiveDate = (Get-Date).AddDays(-($DaysInactive))

$Users = Get-ADUser -SearchScope OneLevel -SearchBase "ou=staff,ou=brummitt,dc=DUNELAND,dc=LOCAL" -Filter { LastLogonDate -lt $InactiveDate } -Properties LastLogonDate |
         Select-Object @{Name="Username";Expression={$_.SamAccountName}},
             Name, LastLogonDate, DistinguishedName

$Users | Export-Csv C:\Temp\InactiveUsers.csv -NoTypeInformation

If you see the users variable you will see that we have a school name and a staff ou inside that. We have that convention for all buildings in our district. How can I scan all first level OUs with the staff OU being the second?

I tried changing the Searchbase to this -SearchBase "ou=staff,ou=*,dc=DUNELAND,dc=LOCAL" but I received this error:

Get-ADUser : Directory object not found 
At line:6 char:10
+ $Users = Get-ADUser -SearchScope OneLevel -SearchBase "ou=staff,ou=*,dc=DUNELAND ...
+ > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.GetADUser
1

1 Answers

1
votes

You can't specify a wildcard in the SearchBase DN, but you could do it like this:

  1. Query all OU's directly under the root
  2. Query each first-level OU's for a "staff" OU
  3. Query each staff OU for the users

Something like:

# 1. Find the first-level OU's
$LevelOne = Get-ADOrganizationalUnit -Filter * -SearchScope OneLevel

# 2. Find the staff OU's
$StaffOUs = $LevelOne |ForEach-Object {
    Get-ADOrganizationalUnit -Filter "Name -like 'Staff'" -SearchBase $_.DistinguishedName -SearchScope OneLevel -ErrorAction SilentlyContinue
}

# 3. Query each staff OU
$StaffOUs |ForEach-Object {
    Get-ADUser -SearchScope OneLevel -SearchBase $_.DistinguishedName -Filter { LastLogonDate -lt $InactiveDate } -Properties LastLogonDate |
    Select-Object @{Name="Username";Expression={$_.SamAccountName}},
        Name, LastLogonDate, DistinguishedName
} |Export-Csv C:\Temp\InactiveUsers.csv -NoTypeInformation