I have to add users to some groups based on their departments. There may be more than 1 group per department.
So most groups which are specific to a department will have the department mentioned in the department attribute for others this field may be empty.
Similarly users in the department also have department mentioned in a custom attribute called departmentnumber. For a a group belonging to a department the department value will be same as departmentnumber attribute for the user.
I use the below command to get the list of groups which are specific to a single department
Get-ADGroup -Filter {department -like "*"} -Property department
Furthermore if I want the list of users who belong to these departmentsm, I can get using the below script
Get-ADGroup -Filter {department -like "*"} -Property department | ForEach {Get-ADUser -Filter {departmentnumber -like $_.department}}
I run into an error in the below script
(Save array of Department groups in a variable and Counter through groups and users who have same department attribute)
$GP=Get-ADGroup -Filter {department -like "*"} -Property department
ForEach {$GP+
Get-ADUser -Filter {departmentnumber -like $GP.department} | ForEach{Add-ADGroupMember -Identity $GP.SamAccountName -Members $_.SamAccountName}
}
Can someone poibt out what is wrong. Is Gp+ the incorrect way to increment the array counter?
Error is:
At line:1 char:8
+ ForEach {$GP+
+ ~
Missing opening '(' after keyword 'foreach'.
At line:1 char:14
+ ForEach {$GP+
+ ~
You must provide a value expression following the '+' operator.
At line:2 char:1
+ Get-ADUser -Filter {departmentnumber -like $GP.department} | ForEach ...
+ ~~~~~~~~~~
Unexpected token 'Get-ADUser' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword