Link to home
Start Free TrialLog in
Avatar of jsawicki
jsawicki

asked on

PowerShell Scripting Arrays with ForEach

I am trying writing a PowerShell script to disable inactive user accounts using arrays.

I found this bit of code on TechNet which parses each domain controller:
# Get the list of all the domain controllers for the current domain
$DCs = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers
foreach ($DC in $DCs)
{
# Set in the LDAP URL the DC hostname and the container DN specified on the command line
$LdapURL = "LDAP://" + $DC.Name + "/" + $Subtree
# Initialize a DirectorySearcher object
$searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$LdapURL)
.
.
}

This code works but requires that I enter the $Subtree (DN of the OU containing the User objects).  
What I need to do is parse the parent OU of the OU containing the user objects and parse through that one too.
Example (Active Directory view -/+ = expand/collapse):

-mydomain@domain.com
     -COMPANY (OU)
         -Region 1($regOU)
             -FAC_ID1 ($siteOU)
                 Users (user objects)
             -FAC_ID2 ($siteOU)
                 Users (user objects)
             +FAC_ID3 ($siteOU)
         -Region 2($regOU)
               -FAC_ID1 ($siteOU)
                  Users (user objects)
              +FAC_ID2 ($siteOU)
              +FAC_ID3 ($siteOU)
         +Region 3 ($regOU)
         +Region 4 ($regOU)
.
.
.
I am thinking the new code should look something like this:
foreach ($DC in $DCs)
{
  foreach ($regOU in $regOUs)
  {
   foreach ($siteOU in $siteOUs)
    {

How do I identify/assign the $regOUs and $siteOUs array values in PowerShell?  
The $siteOUs array could contain upwards of 10 OU objects per ever 1 $regOU (and there are multiples of those too).

Let me know if you require any addition details or clarification.  Thanks
ASKER CERTIFIED SOLUTION
Avatar of chrismerritt
chrismerritt

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jsawicki
jsawicki

ASKER

Appreciate you taking the time to review the extensive question and providing your detailed answer.  Was what i required.
Glad to help.
Avatar of Brent Challis
Microsoft's ActiveDirectory module also makes it easy to work with AD objects.  If you want to get a list of all the inactive accounts you can use the command:
Search-ADAccount -AccountInactive -TimeSpan 100.00:00:00 -Server $computerName | Out-GridView

If you change the piping from Out-GridView to Disable-ADUser to will disable all the accounts that have been inactive for the timespan you define.

Search-ADAccount also supports:
-SearchBase <string>
        Specifies an Active Directory path to search under.