Modifying all users in an OU

A question was submitted via my blog asking how to set all accounts in an OU not to expire.  This can be split into two parts:

  1. Find the user accounts in a particular OU
  2. Set them not to expire

These two posts shoed how to get the users in an OU tree

http://msmvps.com/blogs/richardsiddaway/archive/2012/01/03/get-ad-users-in-an-ou-tree.aspx

http://msmvps.com/blogs/richardsiddaway/archive/2012/01/04/ad-provider-get-all-users-in-an-ou.aspx

While this post covers removing an expiry date from an account the same principles apply to any update

Lets put the two together

$ou = "OU=BlogTests,DC=Manticore,DC=org"            
            
"`nMicrosoft"            
Get-ADUser -ResultSetSize 3000 -SearchBase $ou -Filter * |             
Set-ADUser -Replace @{accountExpires = 0}            
            
"`nAD provider"            
Get-ChildItem -Path AD:\$ou  |             
where {$_.objectclass -eq "user"} |             
foreach {            
 $dn = "cn=$($_.name),$ou"            
 Set-ItemProperty -Path AD:\$dn  -Name accountExpires -Value "0" -Force            
}            
            
"`nQuest"            
Get-QADUser -SizeLimit 3000 -SearchRoot $ou |             
Set-QADUser -ObjectAttributes @{accountExpires = 0}            
            
"`nScript"            
            
$root = [ADSI]"LDAP://$ou"            
$search = [adsisearcher]$root            
$search.Filter = "(&(objectclass=user)(objectcategory=user))"            
$search.SizeLimit = 3000            
$search.FindAll() |            
foreach {            
  $user = $_.GetDirectoryEntry()            
  $user.Put("accountExpires", 0)            
  $user.SetInfo()            
}

For the cmdlets we use   Get-ADuser or Get-QADuser with the search root pointing to the appropriate OU. The results are piped into the matching set cmdlet.

The provider we pipe the results into foreach and use set-itemproperty on the attribute. Notice how we create the distinguished name – we could use the distinguished name property but I just adapted the code for dealing with a single user

The script does an LDAP search of the OU and pipes the results in to foreach. The GetDirectoryEntry() method is used and the resultant object has the account expiry date set to zero.

Published Fri, Feb 24 2012 19:06 by RichardSiddaway

Comments

# re: Modifying all users in an OU

Thank you! I just started trying to learn PS and I really appreciate your assistance and incredibly speedy reply!

Friday, February 24, 2012 5:52 PM by Scott Loudon

# re: Modifying all users in an OU

Pleasure - glad to be able to help

Saturday, February 25, 2012 4:35 AM by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: