Narrow down OU's being audited in PS script

Hey Experts, in the script below, everything is working but the scope of the OU's being audited is too wide.  I need to specify the highest level OU that should be audited.

Example:
DC=Domain
OU=State
-OU=City1
--OU=Agency1
---OU=PC's
---OU=Users
--OU=Agency2
---OU=PC's
---OU=Users

City2
--Agency1
--Agency2

I need to limit the user auditing to just the agency levels to the OU's under City1.  I ran the script and just went through the state level users accounts.  Exciting times.  

Import-Module ActiveDirectory

$disabledOU = "OU=InactiveUsers,DC=my,DC=domain,DC=com"

$users = Get-ADUser -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($user in $users)
{
    Disable-ADAccount -Identity $user.SAMAccountName -WhatIf
    Move-ADObject -Identity $user.SAMAccountName -TargetPath $disabledOU -WhatIf
}

Open in new window

LVL 9
samiam41Asked:
Who is Participating?
 
PberSolutions ArchitectCommented:
Add a Searchbase to your query to point to the target ou

$users = Get-ADUser -SearchBase "OU=City1,OU=State,DC=my,DC=domain,DC=com" -Filter * -Properties SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}

Open in new window


This should only find users within the City1 OU and below.
1
 
samiam41Author Commented:
Brilliant!!
0
 
samiam41Author Commented:
If you can help with my new question, I would appreciate it-> https://www.experts-exchange.com/questions/29072614/Stale-computer-script-PS.html#a42396563
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.