Tee Dub
Tee Dub

Reputation: 3

How to add Sub-OUs in Powershell Script

We have a Powershell script that creates new student accounts, makes necessary changes to existing accounts and moves the accounts to the correct OU based on school. The script worked pretty well previously because the OU structure was pretty flat. All school OUs were located directly under the "District Student Users" OU.

District Student Users

However, now we are getting new schools that don't fit the structure. Instead of being independent school levels, we have added a couple of schools that require sub-OUs. (Indicated under the CompilationSchools). *edit-Added an additional level of OUs under THS indicated by the "AHS" and "BHS"


The script defines the base OU as $base = "OU="+$ou+",OU=District Student Users,DC=district,DC=edu"

I don't know how to include the necessary sub-OUs in the script while not messing up the existing base OU definition.

 # Move AD Object to the new OU
  IF ($newschool -eq 1) {
    Switch ($department)
      {
    "One Middle School" { $ou="OMS" }
    "One High School" { $ou="OHS" }
    "One Elementary" { $ou="OES" }
    default { $ou="z_Unclassified" }
      }
    Write-Host "  Also moved from"$exist.department"to"$department`r
    $base = "OU="+$ou+",OU=District Student Users,DC=district,DC=edu"
    Sleep 2
    Move-ADObject -Identity $dn -TargetPath $base -server $dc }
  ELSEIF ($newschool -eq 2) {
    Write-Host "   Account moved to z_DisabledAccounts OU"`r
    $base = "OU=z_DisabledAccounts,OU=District Student Users,DC=district,DC=edu"
    Sleep 2
    Move-ADObject -Identity $dn -TargetPath $base -server $dc 
  }

Upvotes: 0

Views: 764

Answers (1)

LeeM
LeeM

Reputation: 1248

You can modify your switch statement:

    $compSch= "OU=CompilationSchools"
    Switch ($department)
      {
    "One Middle School" { $ou="OMS" }
    "One High School" { $ou="OHS" }
    "One Elementary" { $ou="OES" }
    "One Compliation HS" { $ou="THS,$compSch" }
    default { $ou="z_Unclassified" }
      }

That's the quick and easy solution and it should work fine. The extra variable is just to save a little typing.

If you might have horrible characters in your OU names like commas (I hope not), or just to save confusion, you might want to be a little less lazy and do a proper concatenation of the OU string, similar to how it's done later.

"One Compliation HS" { $ou="THS," + $compSch }

Upvotes: 1

Related Questions