-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMSADUsersPerGroup.ps1
72 lines (60 loc) · 1.87 KB
/
MSADUsersPerGroup.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function Get-UsersInGroup {
[cmdletbinding()]
param (
[parameter(Mandatory=$true)]
[string]$Object
)
[System.Collections.ArrayList]$Users = @()
$x = Get-ADObject -Identity $Object -Properties SamAccountName
if ($x.ObjectClass -eq "group") {
$y = Get-ADGroup -Identity $Object -Properties Members
$y.Members | %{
$o = Get-ADObject -Identity $_ -Properties SamAccountName
if ($o.ObjectClass -eq "user") {
$null = $Users.Add($o)
}
elseif ($o.ObjectClass -eq "group") {
Get-UsersInGroup -Object $o.DistinguishedName
}
}
} else {
Write-Warning "$($Object) is not a group, it is a $($x.ObjectClass)"
}
$Users | select name | Sort-Object -Property name
}
function RemoveDups {
[cmdletbinding()]
param (
[parameter(Mandatory=$true)]
[System.Collections.ArrayList]$ArrayList
)
$last = ""
$this = ""
[System.Collections.ArrayList]$out = @()
foreach ($a in $ArrayList) {
if ($a -ne $last) {
$null = $out.add($a)
}
$last = $a
}
$out
}
$groupName = Read-Host "group name"
$gn = $groupName -replace " ", ""
$fn = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path + "\" + $gn + "Members.csv"
$gp = Get-ADGroup -Identity "$groupName" #try with sAMAccountName first
if (!$gp) {
#if that failed, try with Name
$gp = Get-ADGroup -Filter "Name -eq '$groupName'"
}
$gm = Get-UsersInGroup -Object ($gp).DistinguishedName | Sort-Object -Property name
[System.Collections.ArrayList]$gpMem = @()
foreach ($m in $gm) {
[void]$gpMem.Add($m.name)
}
$gpMembers = RemoveDups -ArrayList $gpMem
Set-Content $fn -Value $null
foreach ($e in $gpMembers) {
"`"$e`"" | Add-Content $fn
}
Start-Process -FilePath $fn