Link List of GPOs to Sub OUs Based On OU Name

  • 1 December 2016
  • Sean Huggans
Description: 

The following script is useful in cases where you need to link the same set of GPOs (provided in a list) to all sub OUs of OUs matching a given keyword (for example, "Controlled Devices").

Language: 
PowerShell
#########################################################
#
# Name: LinkGPOstoSubOUsBasedOnName.ps1
# Author: Sean Huggans
# Version: 1.0
# Date: 2016.11.30
# Links GPOs provided in a supplied list to OUs provided
# in a supplied list.
#
#########################################################
Import-Module ActiveDirectory
Import-Module GroupPolicy
 
$GPOList = "c:\temp\gpolist.txt"
$OUsNamed = "Controlled Devices"
 
function LinkGPO {
# Create the link on the target
New-GPLink -Name $title -Target $ListedOU -LinkEnabled "Yes" -confirm:$false
# Set the link order on the target
Set-GPLink -Name $title -Target $ListedOU -Order 1 -confirm:$false
# Set the original enforcement setting on the target
Set-GPLink -Name $title -Target $ListedOU -Enforced "No" -confirm:$false
}
 
$OUFilter = Get-ADOrganizationalUnit -Filter "Name -eq '$OUsNamed'"
foreach ($ComputerOU in $OUFilter | Sort) {
 $SubOUs = Get-ADOrganizationalUnit -SearchBase $ComputerOU  -SearchScope Subtree -Filter * | Select-Object DistinguishedName
 foreach ($SubOU in $SubOUs) {
  if (($SubOU.DistinguishedName -notlike "*filter1*") -and ($SubOU.DistinguishedName -notlike "*filter2*") -and ($SubOU.DistinguishedName -notlike "*filter3*"))  {
   echo “———————————————-----------------------------—”
   echo $SubOU.DistinguishedName
   echo “———————————————-----------------------------—”
   ForEach ($title in $(Get-Content $GPOList)) {
    echo $title
    LinkGPO
      }
   echo "---"
   echo ” ”
  } else {
   echo “———————————————-----------------------------—”
   echo $SubOU.DistinguishedName
   echo “———————————————-----------------------------—”
   echo "No GPOs were linked due to filtering."
   echo "---"
   echo ” ”
  }
 }
}
Note: that all applications posted here are posted for use, both commercial and non-commercial, free of charge, and as such are provided without warranty of any kind whatsoever. FMSCUG or any program's author are not responsible for any damages or shortcomings that result from usage of any of these applications.