From 72e4a1acc73f92037b118557159854ece506b832 Mon Sep 17 00:00:00 2001
From: marco <marcotorello@gmail.com>
Date: Tue, 11 May 2021 02:12:25 +0200
Subject: [PATCH] fix big group problem (#204)

* fix big group problem

* fix syntax to pass tests

* Update win_domain_group_membership.ps1

* fix as suggested by @jborean93

* Added changelog fragment

Co-authored-by: Jordan Borean <jborean93@gmail.com>
---
 .../fragments/win_domain_group_membership-large.yml    |  2 ++
 plugins/modules/win_domain_group_membership.ps1        | 10 ++++++----
 2 files changed, 8 insertions(+), 4 deletions(-)
 create mode 100644 changelogs/fragments/win_domain_group_membership-large.yml

diff --git a/changelogs/fragments/win_domain_group_membership-large.yml b/changelogs/fragments/win_domain_group_membership-large.yml
new file mode 100644
index 00000000..6a2715bd
--- /dev/null
+++ b/changelogs/fragments/win_domain_group_membership-large.yml
@@ -0,0 +1,2 @@
+bugfixes:
+- win_domain_group_membership - Handle timeouts when dealing with group with lots of members - https://github.com/ansible-collections/community.windows/pull/204
diff --git a/plugins/modules/win_domain_group_membership.ps1 b/plugins/modules/win_domain_group_membership.ps1
index 878b9fc6..fa729061 100644
--- a/plugins/modules/win_domain_group_membership.ps1
+++ b/plugins/modules/win_domain_group_membership.ps1
@@ -50,7 +50,9 @@ if ($diff_mode) {
     $result.diff = @{}
 }
 
-$members_before = Get-AdGroupMember -Identity $ADGroup @extra_args
+$filter = "(memberOf=$($ADGroup.DistinguishedName))"
+
+$members_before = Get-ADObject -LDAPFilter $filter -Properties sAMAccountName, objectSID @extra_args
 $pure_members = [System.Collections.Generic.List`1[String]]@()
 
 foreach ($member in $members) {
@@ -89,7 +91,7 @@ foreach ($member in $members) {
 
 if ($state -eq "pure") {
     # Perform removals for existing group members not defined in $members
-    $current_members = Get-AdGroupMember -Identity $ADGroup @extra_args
+    $current_members = Get-ADObject -LDAPFilter $filter -Properties sAMAccountName, objectSID @extra_args
 
     foreach ($current_member in $current_members) {
         $user_to_remove = $true
@@ -101,14 +103,14 @@ if ($state -eq "pure") {
         }
 
         if ($user_to_remove) {
-            Remove-ADPrincipalGroupMembership -Identity $current_member -MemberOf $ADGroup -WhatIf:$check_mode -Confirm:$False
+            Remove-ADPrincipalGroupMembership -Identity $current_member -MemberOf $ADGroup -WhatIf:$check_mode -Confirm:$False @extra_member_args
             $result.removed.Add($current_member.SamAccountName)
             $result.changed = $true
         }
     }
 }
 
-$final_members = Get-AdGroupMember -Identity $ADGroup @extra_args
+$final_members = Get-ADObject -LDAPFilter $filter -Properties sAMAccountName, objectSID @extra_args
 
 if ($final_members) {
     $result.members = [Array]$final_members.SamAccountName