I use the following function in a PowerShell script to check and - depending on the value of the $Action - either add or remove an Active Directory User Object from a Security Group.Function Update-Group-Membership ($Action, $ADUser_Properties, $GroupName, $LogPathFileName) {    $CurrentGroupMembers = Get-ADGroupMember -Identity:$GroupName | ? { $_.objectClass -ieq 'user' } | Select-Object -ExpandProperty samAccountName    $ExistingMember = [bool]($ADUser_Properties | ? { $CurrentGroupMembers -contains $_.samAccountName })    If ($Action -eq ADD) {        If ($ExistingMember) {            [ + (Get-Date -format dd/MM/yyyy HH:mm:ss) + ]  ... Update NOT Required: Existing Member of $GroupName | Out-File $LogPathFileName -Append            Write-Host   ... Update NOT Required: Existing Member of $GroupName -ForegroundColor DarkGray              } Else {            # Add to the group            $PSCommand = $ADUser_Properties | Add-ADPrincipalGroupMembership -MemberOf:$GroupName            [ + (Get-Date -format dd/MM/yyyy HH:mm:ss) + ]  ... Updated: Added to $GroupName | Out-File $LogPathFileName -Append            Write-Host   ... Updated: Added to $GroupName -ForegroundColor Yellow                      }    }    If ($Action -eq REMOVE) {        If ($ExistingMember) {            # Remove to the group            $PSCommand = $ADUser_Properties | Remove-ADPrincipalGroupMembership -MemberOf:$GroupName -Confirm $False            [ + (Get-Date -format dd/MM/yyyy HH:mm:ss) + ]  ... Updated: Removed from $GroupName | Out-File $LogPathFileName -Append            Write-Host   ... Updated: Removed from $GroupName -ForegroundColor Yellow        }}   }The function is called as follows:Update-Group-Membership ADD $ADUser_Properties SECURITY_GROUP_NAME $LogPathFileName$ADUser_Properties contains the output of the Get-ADUser command.Whilst this function performs as expected, it is not particularly efficient and takes over a second to check a single user which consequently means processing several hundred users takes several hours.Does anyone have any suggestions on how to improve or fine-tune it?
Inefficient PowerShell function for checking group membership
performance;powershell;active directory