-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathGet-LocalGroupMembership.ps1
338 lines (303 loc) · 15.6 KB
/
Get-LocalGroupMembership.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
Function Get-LocalGroupMembership {
<#
.SYNOPSIS
Recursively list all members of a specified Local group.
.DESCRIPTION
Recursively list all members of a specified Local group. This can be run against a local or
remote system or systems. Recursion is unlimited unless specified by the -Depth parameter.
Alias: glgm
.PARAMETER Computername
Local or remote computer/s to perform the query against.
Default value is the local system.
.PARAMETER Group
Name of the group to query on a system for all members.
Default value is 'Administrators'
.PARAMETER Depth
Limit the recursive depth of a query.
Default value is 2147483647.
.PARAMETER Throttle
Number of concurrently running jobs to run at a time
Default value is 10
.NOTES
Author: Boe Prox
Created: 8 AUG 2013
Version 1.0 (8 AUG 2013):
-Initial creation
.EXAMPLE
Get-LocalGroupMembership
Name ParentGroup isGroup Type Computername Depth
---- ----------- ------- ---- ------------ -----
Administrator Administrators False Domain DC1 1
boe Administrators False Domain DC1 1
testuser Administrators False Domain DC1 1
bob Administrators False Domain DC1 1
proxb Administrators False Domain DC1 1
Enterprise Admins Administrators True Domain DC1 1
Sysops Admins Enterprise Admins True Domain DC1 2
Domain Admins Enterprise Admins True Domain DC1 2
Administrator Enterprise Admins False Domain DC1 2
Domain Admins Administrators True Domain DC1 1
proxb Domain Admins False Domain DC1 2
Administrator Domain Admins False Domain DC1 2
Sysops Admins Administrators True Domain DC1 1
Org Admins Sysops Admins True Domain DC1 2
Enterprise Admins Sysops Admins True Domain DC1 2
Description
-----------
Gets all of the members of the 'Administrators' group on the local system.
.EXAMPLE
Get-LocalGroupMembership -Group 'Administrators' -Depth 1
Name ParentGroup isGroup Type Computername Depth
---- ----------- ------- ---- ------------ -----
Administrator Administrators False Domain DC1 1
boe Administrators False Domain DC1 1
testuser Administrators False Domain DC1 1
bob Administrators False Domain DC1 1
proxb Administrators False Domain DC1 1
Enterprise Admins Administrators True Domain DC1 1
Domain Admins Administrators True Domain DC1 1
Sysops Admins Administrators True Domain DC1 1
Description
-----------
Gets the members of 'Administrators' with only 1 level of recursion.
#>
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias('CN','__Server','Computer','IPAddress')]
[string[]]$Computername = $env:COMPUTERNAME,
[parameter()]
[string]$Group = "Administrators",
[parameter()]
[int]$Depth = ([int]::MaxValue),
[parameter()]
[Alias("MaxJobs")]
[int]$Throttle = 10
)
Begin {
$PSBoundParameters.GetEnumerator() | ForEach {
Write-Verbose $_
}
#region Extra Configurations
Write-Verbose ("Depth: {0}" -f $Depth)
#endregion Extra Configurations
#Define hash table for Get-RunspaceData function
$runspacehash = @{}
#Function to perform runspace job cleanup
Function Get-RunspaceData {
[cmdletbinding()]
param(
[switch]$Wait
)
Do {
$more = $false
Foreach($runspace in $runspaces) {
If ($runspace.Runspace.isCompleted) {
$runspace.powershell.EndInvoke($runspace.Runspace)
$runspace.powershell.dispose()
$runspace.Runspace = $null
$runspace.powershell = $null
} ElseIf ($runspace.Runspace -ne $null) {
$more = $true
}
}
If ($more -AND $PSBoundParameters['Wait']) {
Start-Sleep -Milliseconds 100
}
#Clean out unused runspace jobs
$temphash = $runspaces.clone()
$temphash | Where {
$_.runspace -eq $Null
} | ForEach {
Write-Verbose ("Removing {0}" -f $_.computer)
$Runspaces.remove($_)
}
} while ($more -AND $PSBoundParameters['Wait'])
}
#region ScriptBlock
$scriptBlock = {
Param ($Computer,$Group,$Depth,$NetBIOSDomain,$ObjNT,$Translate)
$Script:Depth = $Depth
$Script:ObjNT = $ObjNT
$Script:Translate = $Translate
$Script:NetBIOSDomain = $NetBIOSDomain
Function Get-LocalGroupMember {
[cmdletbinding()]
Param (
[parameter()]
[System.DirectoryServices.DirectoryEntry]$LocalGroup
)
# Invoke the Members method and convert to an array of member objects.
#Change3 comment from web page by Craig Dempsey to fixe Powershell 5.0 issue
#$Members= @($LocalGroup.psbase.Invoke("Members"))
$Members= @($LocalGroup.psbase.Invoke("Members")) | foreach{([System.DirectoryServices.DirectoryEntry]$_)}
$Counter++
ForEach ($Member In $Members) {
Try {
#Change3
#$Name = $Member.GetType().InvokeMember("Name", 'GetProperty', $Null, $Member, $Null)
#$Path = $Member.GetType().InvokeMember("ADsPath", 'GetProperty', $Null, $Member, $Null)
$Name = $Member.InvokeGet("Name")
$Path = $Member.InvokeGet("AdsPath")
# Check if this member is a group.
#Change3
#$isGroup = ($Member.GetType().InvokeMember("Class", 'GetProperty', $Null, $Member, $Null) -eq "group")
$isGroup = ($Member.InvokeGet("Class") -eq "group")
#region Change1 by Kensel
#Remove the domain from the computername to fix the type comparison when supplied with FQDN
IF ($Computer.Contains('.')){
$Computer = $computer.Substring(0,$computer.IndexOf('.'))
}
#endregion Change1 by Kensel
If (($Path -like "*/$Computer/*")) {
$Type = 'Local'
} Else {$Type = 'Domain'}
#Change2 by Kensel - Add the Group to the output
New-Object PSObject -Property @{
Computername = $Computer
Name = $Name
Type = $Type
ParentGroup = $LocalGroup.Name[0]
isGroup = $isGroup
Depth = $Counter
Group = $Group
}
If ($isGroup) {
# Check if this group is local or domain.
#$host.ui.WriteVerboseLine("(RS)Checking if Counter: {0} is less than Depth: {1}" -f $Counter, $Depth)
If ($Counter -lt $Depth) {
If ($Type -eq 'Local') {
If ($Groups[$Name] -notcontains 'Local') {
$host.ui.WriteVerboseLine(("{0}: Getting local group members" -f $Name))
$Groups[$Name] += ,'Local'
# Enumerate members of local group.
Get-LocalGroupMember $Member
}
} Else {
If ($Groups[$Name] -notcontains 'Domain') {
$host.ui.WriteVerboseLine(("{0}: Getting domain group members" -f $Name))
$Groups[$Name] += ,'Domain'
# Enumerate members of domain group.
Get-DomainGroupMember $Member $Name $True
}
}
}
}
} Catch {
$host.ui.WriteWarningLine(("GLGM{0}" -f $_.Exception.Message))
}
}
}
Function Get-DomainGroupMember {
[cmdletbinding()]
Param (
[parameter()]
$DomainGroup,
[parameter()]
[string]$NTName,
[parameter()]
[string]$blnNT
)
Try {
If ($blnNT -eq $True) {
# Convert NetBIOS domain name of group to Distinguished Name.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $Translate, (3, ("{0}{1}" -f $NetBIOSDomain.Trim(),$NTName)))
$DN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $Translate, 1)
$ADGroup = [ADSI]"LDAP://$DN"
} Else {
$DN = $DomainGroup.distinguishedName
$ADGroup = $DomainGroup
}
$Counter++
ForEach ($MemberDN In $ADGroup.Member) {
$MemberGroup = [ADSI]("LDAP://{0}" -f ($MemberDN -replace '/','\/'))
#Change2 by Kensel - Add the Group to the output
New-Object PSObject -Property @{
Computername = $Computer
Name = $MemberGroup.name[0]
Type = 'Domain'
ParentGroup = $NTName
isGroup = ($MemberGroup.Class -eq "group")
Depth = $Counter
Group = $Group
}
# Check if this member is a group.
If ($MemberGroup.Class -eq "group") {
If ($Counter -lt $Depth) {
If ($Groups[$MemberGroup.name[0]] -notcontains 'Domain') {
Write-Verbose ("{0}: Getting domain group members" -f $MemberGroup.name[0])
$Groups[$MemberGroup.name[0]] += ,'Domain'
# Enumerate members of domain group.
Get-DomainGroupMember $MemberGroup $MemberGroup.Name[0] $False
}
}
}
}
} Catch {
$host.ui.WriteWarningLine(("GDGM{0}" -f $_.Exception.Message))
}
}
#region Get Local Group Members
$Script:Groups = @{}
$Script:Counter=0
# Bind to the group object with the WinNT provider.
$ADSIGroup = [ADSI]"WinNT://$Computer/$Group,group"
Write-Verbose ("Checking {0} membership for {1}" -f $Group,$Computer)
$Groups[$Group] += ,'Local'
Get-LocalGroupMember -LocalGroup $ADSIGroup
#endregion Get Local Group Members
}
#endregion ScriptBlock
Write-Verbose ("Checking to see if connected to a domain")
Try {
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Root = $Domain.GetDirectoryEntry()
$Base = ($Root.distinguishedName)
# Use the NameTranslate object.
$Script:Translate = New-Object -comObject "NameTranslate"
$Script:objNT = $Translate.GetType()
# Initialize NameTranslate by locating the Global Catalog.
$objNT.InvokeMember("Init", "InvokeMethod", $Null, $Translate, (3, $Null))
# Retrieve NetBIOS name of the current domain.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $Translate, (1, "$Base"))
[string]$Script:NetBIOSDomain =$objNT.InvokeMember("Get", "InvokeMethod", $Null, $Translate, 3)
} Catch {Write-Warning ("{0}" -f $_.Exception.Message)}
#region Runspace Creation
Write-Verbose ("Creating runspace pool and session states")
$sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$runspacepool = [runspacefactory]::CreateRunspacePool(1, $Throttle, $sessionstate, $Host)
$runspacepool.Open()
Write-Verbose ("Creating empty collection to hold runspace jobs")
$Script:runspaces = New-Object System.Collections.ArrayList
#endregion Runspace Creation
}
Process {
ForEach ($Computer in $Computername) {
#Create the powershell instance and supply the scriptblock with the other parameters
$powershell = [powershell]::Create().AddScript($scriptBlock).AddArgument($computer).AddArgument($Group).AddArgument($Depth).AddArgument($NetBIOSDomain).AddArgument($ObjNT).AddArgument($Translate)
#Add the runspace into the powershell instance
$powershell.RunspacePool = $runspacepool
#Create a temporary collection for each runspace
$temp = "" | Select-Object PowerShell,Runspace,Computer
$Temp.Computer = $Computer
$temp.PowerShell = $powershell
#Save the handle output when calling BeginInvoke() that will be used later to end the runspace
$temp.Runspace = $powershell.BeginInvoke()
Write-Verbose ("Adding {0} collection" -f $temp.Computer)
$runspaces.Add($temp) | Out-Null
Write-Verbose ("Checking status of runspace jobs")
Get-RunspaceData @runspacehash
}
}
End {
Write-Verbose ("Finish processing the remaining runspace jobs: {0}" -f (@(($runspaces | Where {$_.Runspace -ne $Null}).Count)))
$runspacehash.Wait = $true
Get-RunspaceData @runspacehash
#region Cleanup Runspace
Write-Verbose ("Closing the runspace pool")
$runspacepool.close()
$runspacepool.Dispose()
#endregion Cleanup Runspace
}
}
Set-Alias -Name glgm -Value Get-LocalGroupMembership