Redirecting Users and Computers Containers with Powershell

By | February 20, 2015

The default location for newly provisioned user and computer objects are (respectively) the Users and Computers containers.  Since Windows Server 2003 Active Directory the option has been available to redirect these to OUs that you specificy.  Why would you want to do this?  Well, the Users and Computers containers are just that – container objects and not OUs.  You can apply Group Policy to OUs but not to containers. 

 As an example, you might have important security settings such as AppLocker application whitelisting that you apply to your computers via GPOs.  If you have computer objects in the default Computers container they will not be picking up those policies.

 I recommend to all my customers that they redirect the Users and Computers containers to OUs that are locked down with highly restrictive Group Policies.  This measure effectively forces the admins to move those objects to where they should be located in the OU structure.  The most well-known method of performing the redirection is to use the redirusr and redircmp utilities that are built-into the operating system.  The process is described on Technet (https://technet.microsoft.com/en-us/library/cc772758(v=ws.10).aspx)

 Of course we now have PowerShell as an alternative option.  I thought it would be fun to see how easy it would be to perform the redirection using a script.  Here’s what I came up with (seems to do the job).

 

## Specify the new targets for redirection
$dnc = (Get-ADRootDSE).DefaultNamingContext
# Users
$newusers = "OU=Redirected Users," + $dnc
# Computers
$newcomps = "OU=Redirected Computers," + $dnc

# Get the current targets (from wellKnownObjects attribute)
$wkos = Get-ADObject -Identity $dnc -pr wellKnownObjects `
| select -ExpandProperty wellKnownObjects

# Find the Users container value in the attribute
$curuwko = $wkos | ? {$_ -like "*CN=Users,*"}
# Split the value into its constituent parts
$datusers = $curuwko.split(":")

# Find the Computers container value in the attribute
$curcwko = $wkos | ? {$_ -like "*CN=Computers,*"}
# Split the value into its constituent parts
$datcomps = $curcwko.split(":")

# Build the new value for Users
$newuwko = $datusers[0] + ":" + $datusers[1] + ":" + $datusers[2] + ":" + $newusers
# Build the new value for Computers
$newcwko = $datcomps[0] + ":" + $datcomps[1] + ":" + $datcomps[2] + ":" + $newcomps

## Replace the old values with the new
$dc = (Get-ADDomainController).name
Set-ADObject $dnc -add @{wellKnownObjects = $newuwko} `
-Remove @{wellKnownObjects = $curuwko} -Server $dc
Set-ADObject $dnc -add @{wellKnownObjects = $newcwko} `
-Remove @{wellKnownObjects = $curcwko} -Server $dc

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.