I have an almost working script but am getting stuck at one part. What i need to do is to read a CSV file with two columns (Department, GroupName) and add any user whose department attribute matches the department column to the Group. That part is working except for the statement that is supposed to filter out current members of the group. I also need the script to be able to look at the current group members and then remove any users who do not match one of the departments from the CSV file. i.e. so if a user transfers but was never removed from group this script will remove the access. This is the part i’m getting stuck at. I am getting the error “Get-ADUser : A parameter cannot be found that matches parameter name ‘SamAccountName’”. Also not sure the remove part is written properly for what i need. Any assistance or guidance would be greatly appreciated
Thanks
Here is what i have:
#Import the AD module
import-module ActiveDirectory
#Enter path to CSV file containing headers for ADDepartment,GroupName
$CSVFile = "\\server\folder\departmentgroups.csv"
#Enter Log file path
$LogFile = "\\server\folder\log.txt"
#Get todays date
$today = Get-Date -DisplayHint Date
#Imports data from CSV file containing department names and group names - data is case sensitive
import-csv $csvFile | foreach {
#Adds users to group based on attributes
$dept = $_.DeptName
$ADGroup = $_.GroupName
$user = Get-ADUser -LDAPFilter "(&((Department=$dept)(useraccountcontrol=512)(!memberOf=$ADGroup)))" | ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ADGroup
Write-Output "$Today,$Dept,$user,DeptMatch-Was-Added-To-Group" >> $LogFile
}
#Remove any user no longer in department
$groupmember = @(Get-ADGroupMember -Identity $ADGroup | Select-Object -expandproperty SamAccountName)
If(!($groupmember)) {Write-Output "$Today,$Dept,Group-Was-Empty" >>$LogFile} #if no members are in the group write it to log file
Else {$nolongermember = $groupmember | % {Get-ADUser -SamAccountName $_} | Where-Object {$_.department -ne $dept}
#if more then one user is found in the above line, the get-aduser fails with 'idenity' specified method is not supported - so i think i need to do something like foreach but struggling to figure this part out
}
If(!($nolongermember)) {Write-Output "$Today,$Dept,No-Users-To-Remove" >> $LogFile}
Else {Remove-ADGroupMember $ADGroup $nolongermember
Write-Output "$Today,$Dept,$nolongermember,DeptMisMatch-Was-Removed-From-Group" >>$logfile
}
}