MutinyMate
MutinyMate

Reputation: 13

Trying to script adding users to a Group

I'm trying to create a simple script that will automate membership to a security group for my org. I think my variables are coming back empty and are likely either defined wrong or I messed up the syntax somehow. Hoping someone here can help me see the error in my ways!

I am going to edit the code below to better explain my issue. The attribute I am calling can either have a value of M or it is null.

If I run the following command, I get back a list of users who have extensionattribute6 = M

get-aduser -filter {extensionattribute6 -like 'M*'}

If I attempt to add in the section that specifies OU, the results become null. I guess all I'm asking is if there is a syntax mistake with the OUs or, if not, if anyone could hazard a guess as to what I am doing wrong. :)

$OU = "ou=ou1,ou=ou2,ou=ou3,dc=dc1,dc=dc2"
get-aduser -filter {extensionattribute6 -like 'M*'} -searchbase $OU

Upvotes: 0

Views: 185

Answers (2)

MutinyMate
MutinyMate

Reputation: 13

I arrived at a solution to this. I needed to call a new variable, borrowing heavily from what Jawad suggested.

The code I settled on is as follows.

$Managers = @()
$Managers += get-aduser -filter * -searchbase "ou=ou1,ou=ou2,ou=ou3,dc=dc1,dc=dc2" -properties extensionattribute6 | where-object{$_.extensionattribute6 -like 'M*'}
foreach ($Manager in $Managers) {add-adgroupmember -identity <groupname> -members $Manager}

Upvotes: 0

Jawad
Jawad

Reputation: 11364

When you use the filter and like operator, you have to use the * on the right side of the statement.

$managers = Get-ADUser -SearchBase $OU -Filter "extensionattribute6 -like 'M*'"

This will add a list of AD Users that have a value that Starts with M in extensionattribute6. If you dont add the * to the right side, 'M', then it will look for all users with an extensionAttribute6 value that equals M.

If you are comparing them to be equal, then you can use -eq for equality (without stars * inside quote)

$managers = Get-ADUser -SearchBase $OU -Filter "extensionattribute6 -eq 'M'"

If you have multiple specific OUs you want to go over, might i suggest using a list of these OUs and iterating over them.

$OUs = @()
$OUs += "OU=OU1,DC=domain,dc=com"
$OUs += "OU=OU2,OU=someParent,dc=domain,dc=com"
...

$managers = @()
foreach($OU in $OUs) {
  $managers += Get-ADUser -SearchBase $OU -Filter "extensionattribute6 -eq 'M'"
}

Upvotes: 2

Related Questions