I'm trying to check our users in AD to see if they are part of a group, and if they're not add them to it.
The script I have doesn't seem to be working.
*Import-Module ActiveDirectory
$Grpex26Month = "EX-Retention 26 Months"
$Grpex13Month = "EX-Retention 13 Months"
Function Check-IsGroupMember{
Param($user,$grp)
$strFilter = "(&(objectClass=Group)(name=" + $grp +"))"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$colResults = $objSearcher.FindOne()
$objItem = $colResults.Properties
([string]$objItem.member).contains($user)
}
$userList = get-aduser -f {surname -like 'm*'}
Foreach ($user in $userList) {
$Check = Check-IsGroupMember $user $grpex13month
If ($Check -eq 'False') {
Add-adgroupmember $grpex13month $user
write-host $user.Name
}
}*
Now this is a script I modified that previously removed from one group and adding to another but I thought the changes above would still be ok. I'm also only searching for just 'M' at present as I know there is a user in this section that requires this.
This user isn't even being found...this is an example of response I'm getting for all the users apart from the new ones that were set up after this script was first written.
MLastName, FirstName
Add-adgroupmember : The specified account name is already a member of the group
At \\ServerName\DataUsers$\DKendall\Scripts\Exchange groupremoval.ps1:31 char:1
+ Add-adgroupmember $grpex13month $user
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (EX-Retention 13 Months:ADGroup)[Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1378,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember