1

everyone. This question is going to be an easy answer for people whom are experienced in Powershell which I am not.

For unintentional reasons, we have a large number of users who have had a certain attribute changed on their accounts (adminCount). I want this attribute to be cleared instead of 1 and have found a script to do so:

set-aduser <username> -remove @{adminCount=1}

$user = get-aduser <username> -properties ntsecuritydescriptor

$user.ntsecuritydescriptor.SetAccessRuleProtection($false,$true)

set-aduser <username> -replace @{ntsecuritydescriptor=$user.ntsecuritydescriptor}

What I need to do now is run this command for every user in a certain OU (which there are thousands). If anyone could help me come up with a loop that looks like the following, I would appreciate it:

For each user in (Certain Searchbase/OU)
     Run script

Thanks in advance, everyone!

EDIT: Currently, I have the following but am worried to test it since I am a Powershell noob and I only have a production environment right now:

$users = Get-ADUser -ldapfilter “(objectclass=user)” -searchbase “ou=companyusers,dc=enterpriseit,dc=co”
ForEach($user in $users)
{
set-aduser $user -remove @{adminCount=1}

$user = get-aduser $user -properties ntsecuritydescriptor

$user.ntsecuritydescriptor.SetAccessRuleProtection($false,$true)

set-aduser $user -replace @{ntsecuritydescriptor=$user.ntsecuritydescriptor}

 
}
  • If you are worried, then test it! If you only have one environment, at least make an isolated OU and test that. – dugas Aug 11 '20 at 15:43
  • I added the WhatIf parameter in the example below, which you can use to see what operation would take place instead of actually performing it, BUT I WOULD NOT use it as a substitute for proper testing. – dugas Aug 11 '20 at 16:00

1 Answers1

0

You can use the SearchBase parameter to specify the OU when calling the Get-Aduser cmdlet. Pipe that to the ForEach-Object cmdlet, and perform your operations.

NOTE: I assigned the $_ variable to the variable $user just to demonstrate more clearly, since you mentioned you are new to PS.

Get-Aduser -Filter * -SearchBase 'OU=foo,OU=bar,DC=domain,DC=com' -properties ntsecuritydescriptor | 
ForEach-Object { 

$user = $_; 
Write-Host "Performing operations on: $($user.Name)"

# DO Stuff with the user identity. 

$user | Set-ADUser -Remove @{adminCount=1} -WhatIf

$user.ntsecuritydescriptor.SetAccessRuleProtection($false,$true)

$user | Set-ADUser -Replace @{ntsecuritydescriptor=$user.ntsecuritydescriptor} -WhatIf

}
dugas
  • 12,025
  • 3
  • 45
  • 51