Checking for Membership of Groups Based on Wildcard (Powershell)

1k views Asked by At

I'm working on a PowerShell script to bulk amend users but I'm running into a wall with a specific part of it.

Currently there are a series of groups within my organisation that begin with "RIS_" - new groups are added and removed frequently so my idea was to create a script that can check every user listed in a .csv (Reference = $Username) to see if they belong in a group starting with "RIS_".

The base group for example is "RIS_ReadOnly" which grants basic access to an application used within our organisation. The other groups represent various access levels with different permissions, but being a member of multiple groups will always force the lowest possible permissions. This is something I don't have control over so I can't push for a change to the way that works.

The script itself pulls from a .csv file - that whole part is sorted and working.

The user should only be a member of one of these groups at a time, and our usual process involves adding them to the basic ReadOnly group. However this doesn't take into account existing users who are returning to work, who might have elevated access and therefore will lose access when being added to the ReadOnly group. Due to the amount of staff coming and going, we can't realistically check each account for existing memberships, hence the script.

This command needs to check if the user is a member of a group starting with "RIS_". If the user is NOT in a group, then it will be added to the group specified in the .csv (Reference = $RIS). If the user IS in a group, then it will write a message and proceed to the next stage of the code, without adding them to anything.

Everything I've found online has pointed to first getting the groups themselves and listing the members, but this won't work due to the fact that the number of groups changes over time and there are a massive amount of users in each group. Is there any way to set this up with an "IF" statement? I've tried multiple ways of doing it but the script either doesn't add anything at all or adds the groups regardless.

Here is what I've currently got but obviously it isn't working. Any tips?

If ( ($User.MemberOf -like "RIS_" ) )
{
write-verbose "User is already a member of a RIS group" 
else
Add-ADGroupMember -Identity "$RIS" -Members $Username
}

Below is the full script (please excuse the mess of a novice)

CLS


# Import active directory module for running AD cmdlets

Import-Module activedirectory
  

#Store the data from ADAmend.csv in the $ADUsers variable

$ADUsers = Import-csv "\\nuth-it01\workstore\Service Desk\Account Admin Scripts\02 - Amend\01 User - Generic\ADAmend.csv"


#Loop through each row containing user details in the CSV file 

foreach ($User in $ADUsers)
{

    #Read user data from each field in each row and assign the data to a variable as below
        
    $Username   = $User.username
    $Password   = $User.password
    $Firstname  = $User.firstname
    $Lastname   = $User.lastname
    $employeeID = $User.EmployeeID
    $email      = $User.email
    $jobtitle   = $User.jobtitle
    $department = $User.department
    $DOB = $User.DOB
    $INC = $User.INC # INC Identifier - can contain additonal text if account was reactivated/amended
    $GMSN = $User.GMSN # Identifier for GMC and Student Number
    $HomeDrive = $User.Homedrive # Identifier for Home Drive Group
    $AUF = $User.AUF # Identifier for AUD Form completion (Y/N - default "N")
    $AddGrp1 = $User.AddGrp1 # Catchall for additional groups if requested (Can be left blank)
    $AddGrp2 = $User.AddGrp2 # Catchall for additional groups if requested (Can be left blank)
    $AddGrp3 = $User.AddGrp3 # Catchall for additional groups if requested (Can be left blank)
    $eRescue = $User.Erescue # eRescue-AHCare / eRescue-RegNurse / eRescue-SenMedic / eRescue-Medic
    $RIS = $User.RIS # RIS_ReadOnly / RIS_Radiologists / RIS_Radiographers / RIS_Secretaries / RIS_Nurse
    $PACS = $User.PACS # PACS_Clinicians / PACS_Radiologists / PACS_Radiographers / PACS_Secretaries

# Following code adds user to "Xenapp Erecord Downtime" group and enables account. This may return errors if the user is already a member or the account isn't disabled but they can be ignored

Add-ADGroupMember -Identity "Xenapp Erecord Downtime" -Members $Username
Remove-ADGroupMember -Identity "Disabled_Users" -Members $Username -Confirm:$False
Enable-ADAccount -Identity $Username
Clear-ADAccountExpiration -Identity $Username


# Adds the INC into the telephone notes - if this field is blank (it shouldn't be) then nothing will be changed.

$i = Get-ADUser $Username -Properties info | %{ $_.info}  
Set-ADUser $Username -Replace @{info="$($i) `r`n $INC"}


# This next set of code identifies if a cell is left blank in the input sheet, and ignores it if this is the case (prevents wiping pre-existing fields)

# NOTE: If input sheet is modified, this code will need to be modified too

If(-not [string]::IsNullOrWhiteSpace($User.DOB) )
{
Set-ADUser -Identity $Username -Replace @{extensionAttribute10="$DOB"} # Add DOB
}

If(-not [string]::IsNullOrWhiteSpace($User.password) )
{
Set-ADAccountPassword -Identity $Username -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$Password" -Force)  # changes password to specified string - if left blank will not change password
Set-ADUser -Identity $Username -ChangePasswordAtLogon $True # Forces password change at logon - if password field is left blank this will be ignored
}

If(-not [string]::IsNullOrWhiteSpace($User.firstname) ) 
{
Set-ADUser -Identity $Username -GivenName $Firstname
}

If(-not [string]::IsNullOrWhiteSpace($User.lastname) ) 
{
Set-ADUser -Identity $Username -Surname $Lastname
}



If(-not [string]::IsNullOrWhiteSpace($User.EmployeeID) )
{
Set-ADUser -Identity $Username -EmployeeID $EmployeeID
}

If(-not [string]::IsNullOrWhiteSpace($User.Jobtitle) )
{
Set-ADUser -Identity $Username -Description $jobtitle
}

If(-not [string]::IsNullOrWhiteSpace($User.Department) )
{
Set-ADUser -Identity $Username -Office $department
}

If(-not [string]::IsNullOrWhiteSpace($User.GMSN) )
{
Set-ADUser -Identity $Username -Replace @{extensionAttribute14="$GMSN"} # Add GMC or Student Number
}

If(-not [string]::IsNullOrWhiteSpace($User.AUF) )
{
Set-ADUser -Identity $Username -Replace @{extensionAttribute1="$AUF"} # Has AUF form been signed?
}

If(-not [string]::IsNullOrWhiteSpace($User.Email) )
{
Set-ADUser -Identity $Username -EmailAddress $email
}

If(-not [string]::IsNullOrWhiteSpace($User.HomeDrive) )
{
Add-ADGroupMember -Identity "$HomeDrive" -Members $Username # Adds user to homedrive
}

If(-not [string]::IsNullOrWhiteSpace($User.AddGrp1) )
{
Add-ADGroupMember -Identity "$AddGrp1" -Members $Username
}

If(-not [string]::IsNullOrWhiteSpace($User.AddGrp2) )
{
Add-ADGroupMember -Identity "$AddGrp2" -Members $Username
}

If(-not [string]::IsNullOrWhiteSpace($User.AddGrp3) )
{
Add-ADGroupMember -Identity "$AddGrp3" -Members $Username
}

If(-not [string]::IsNullOrWhiteSpace($User.eRescue) )
{
Add-ADGroupMember -Identity "$eRescue" -Members $Username
}


If ( ($User.MemberOf -like "RIS_*" ) )
{
write-verbose "User is already a member of a RIS group" 
else

Add-ADGroupMember -Identity "$RIS" -Members $Username
}

If(-not [string]::IsNullOrWhiteSpace($User.PACS) )
{
Add-ADGroupMember -Identity "$PACS" -Members $Username
}

    Write-Warning "$Username Amended"

}

I've also attached a screenshot of the input csv below:

ADAmend.csv

1

There are 1 answers

2
LosFla On

if you want to check if the user is already member of this group you can try to check the user directly in Active Directory like this:

if ((Get-ADUser $Username -Properties *).memberof | Where-Object {$_ -like 'CN=RIS_*'})
{
    write-verbose "User is already a member of a RIS group" 
}
else
{
    Add-ADGroupMember -Identity $RIS -Members $Username
}