SimpleADAdmin.psm1
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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 |
Class SAGroup { [string] $Name [string] $SamAccountName [string] $Description [string] $Info [string] $Email [string] $DistinguishedName [guid] $ObjectGUID [string] $ObjectSID [string[]] $MemberOf [string[]] $Members [string] $ManagedBy [string] $GroupCategory [string] $GroupScope [datetime] $WhenCreated SAGroup () { Write-Error "You must specify the SamAccountName of the group you want to look at" -ErrorAction Stop } SAGroup ( [string]$Identity ) { $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$Identity))" $Found = @($Searcher.FindOne()) If ($null -eq $Found.properties.samaccountname) { Write-Error "Unable to find ""$Identity""" -ErrorAction Stop } $this.SamAccountName = $Found.properties.samaccountname | Select-Object -First 1 $this.EnumerateFields() $this | Add-Member -MemberType ScriptProperty -Name LastModified -Value { $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$($this.SamAccountName)))" $Found = $Searcher.FindOne() # Enumerate LastModified Write-Output $Found.properties.whenchanged | Select-Object -First 1 $this.EnumerateFields() } # Using default display properties to order the list properly $DefaultDisplayProperties = @( "Name" "SamAccountName" "Description" "Info" "Email" "DistinguishedName" "ObjectGUID" "ObjectSID" "MemberOf" "Members" "ManagedBy" "GroupCategory" "GroupScope" "WhenCreated" "LastModified" ) $this | Add-Member -Force -MemberType MemberSet PSStandardMembers ([System.Management.Automation.PSMemberInfo[]]@(New-Object System.Management.Automation.PSPropertySet("DefaultDisplayPropertySet",[String[]]$DefaultDisplayProperties))) } hidden [void] EnumerateFields() { $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$($this.SamAccountName)))" $Found = @($Searcher.FindOne()) #Thanks Richard Siddaway for breaking this out $GroupTypes = @{ 2 = [PSCustomObject]@{Category="Distribution";Scope="Global"} 4 = [PSCustomObject]@{Category="Distribution";Scope="DomainLocal"} 8 = [PSCustomObject]@{Category="Distribution";Scope="Universal"} -2147483646 = [PSCustomObject]@{Category="Security";Scope="Global"} -2147483644 = [PSCustomObject]@{Category="Security";Scope="DomainLocal"} -2147483643 = [PSCustomObject]@{Category="Security";Scope="BuiltinLocal"} -2147483640 = [PSCustomObject]@{Category="Security";Scope="Universal"} } $this.Name = $Found.properties.name | Select-Object -First 1 $this.Description = $Found.properties.description | Select-Object -First 1 $this.Info = $Found.properties.info | Select-Object -First 1 $this.Email = $Found.properties.mail | Select-Object -First 1 $this.DistinguishedName = $Found.properties.distinguishedname | Select-Object -First 1 $this.ObjectGUID = New-Object GUID(,($Found.properties.objectguid | Select-Object -First 1)) $this.ObjectSID = (New-Object System.Security.Principal.SecurityIdentifier(($Found.properties.objectsid | Select-Object -First 1),0)).Value $this.MemberOf = $Found.properties.memberof $this.Members = $Found.properties.member $this.ManagedBy = $Found.properties.managedby | Select-Object -First 1 $this.GroupCategory = $GroupTypes[($Found.properties.grouptype | Select-Object -First 1)].Category $this.GroupScope = $GroupTypes[($Found.properties.grouptype | Select-Object -First 1)].Scope $this.WhenCreated = $Found.properties.whencreated | Select-Object -First 1 } hidden [PSCustomObject[]] GetMemberObject([string]$dn, [boolean]$Recurse) { $Results = New-Object -TypeName System.Collections.ArrayList $Searcher = [ADSISearcher]"((distinguishedName=$dn))" $Found = @($Searcher.FindOne()) If ($Found.Count -eq 0) { Write-Warning "Unable to find ""$dn""" } Else { If (($Found.properties.objectclass | Select-Object -Last 1) -eq "group" -and $Recurse) { $subResults = $this.GetMembersFromGroup($dn) ForEach ($Result in $subResults) { $null = $Results.Add($Result) } } Else { $null = $Results.Add([PSCustomObject]@{ Member = $Found.properties.name | Select-Object -First 1 SamAccountName = $Found.properties.samaccountname | Select-Object -First 1 ObjectClass = $Found.properties.objectclass | Select-Object -Last 1 }) } } Return $Results } hidden [PSCustomObject[]] GetMembersFromGroup ([string]$dn) { $Results = $null $Searcher = [ADSISearcher]"((distinguishedName=$dn))" $Found = @($Searcher.FindOne()) If ($Found.Count -eq 0) { Write-Warning "Unable to find ""$dn""" } Else { $Results = ForEach ($Member in ($Found.properties.member)) { $this.GetMemberObject($Member, $true) } } Return $Results } hidden [PSCustomObject] ValidateUserName ([string]$Identity) { $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$Identity))" $Found = $Searcher.FindOne() If ($null -eq $Found.properties.samaccountname) { Write-Error "User name ""$Identity"" was not found" -ErrorAction Stop } $Result = [PSCustomObject]@{ Name = $Found.Properties.name DN = $Found.properties.distinguishedname } Return $Result } [PSCustomObject[]] GetMembers() { $Results = ForEach ($Member in $this.Members) { $this.GetMemberObject($Member, $false) } Return $Results } [PSCustomObject[]] GetMembersRecursive() { $Results = ForEach ($Member in $this.Members) { $this.GetMemberObject($Member, $true) } Return $Results } [void] AddMember ([string]$Identity) { $User = $this.ValidateUserName($Identity) $GroupObj = [ADSI]"LDAP://$($this.DistinguishedName)" $GroupObj.Add("LDAP://$($User.DN)") Write-Verbose "Added ""$($User.Name)"" to Group ""$($this.Name)"" which will take a few minutes to show up in `$SAGroup" -Verbose } [void] RemoveMember ([string]$Identity) { $User = $this.ValidateUserName($Identity) $GroupObj = [ADSI]"LDAP://$($this.DistinguishedName)" $GroupObj.Remove("LDAP://$($User.DN)") Write-Verbose "Removed ""$($User.Name)"" from group ""$($this.Name)""" -Verbose } } Class SAUser { [string] $Name [string] $SamAccountName [string] $Title [string] $Description [string] $GivenName [string] $Surname [string] $Email [boolean] $PasswordNeverExpires [boolean] $PasswordNotRequired [string] $DistinguishedName [string] $UserPrincipalName [guid] $ObjectGUID [string] $ObjectSID [string[]] $MemberOf [string] $Manager [string] $LastLogon = "Unknown" [boolean] $LockedOut [int] $BadPasswordCount [boolean] $PasswordExpired [datetime] $PasswordLastSet SAUser () { Write-Error "You must provide a username" -ErrorAction Stop } SAUser ( [string]$Identity ) { $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$Identity))" $Found = $Searcher.FindOne() If ($null -eq $Found.properties.samaccountname) { Write-Error "Unable to locate user name ""$Identity""" -ErrorAction Stop } # Fill in the object $this.SamAccountName = $Found.properties.samaccountname $this.EnumerateFields() # Add Enabled field, and field refresh $this | Add-Member -MemberType ScriptProperty -Name Enabled -Value { $ACCOUNTDISABLE = 0x000002 $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$($this.SamAccountName)))" $Found = $Searcher.FindOne() Write-Output (-not [bool]($Found.userAccountControl -band $ACCOUNTDISABLE)) $this.EnumerateFields() } # Set Default property view $DefaultDisplayProperties = @( "Name" "SamAccountName" "Title" "Enabled" "LockedOut" "BadPasswordCount" "LastLogon" ) $this | Add-Member -Force -MemberType MemberSet PSStandardMembers ([System.Management.Automation.PSMemberInfo[]]@(New-Object System.Management.Automation.PSPropertySet("DefaultDisplayPropertySet",[String[]]$DefaultDisplayProperties))) } hidden [void] EnumerateFields () { $DONT_EXPIRE_PASSWORD = 0x010000 $PASSWORD_EXPIRED = 0x800000 $ADS_UF_PASSWD_NOTREQD = 0x0020 $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$($this.SamAccountName)))" $Found = $Searcher.FindOne() $this.Name = $Found.properties.displayname | Select-Object -First 1 $this.SamAccountName = $Found.properties.samaccountname | Select-Object -First 1 $this.Title = $Found.properties.title | Select-Object -First 1 $this.Description = $Found.properties.description | Select-Object -First 1 $this.GivenName = $Found.properties.givenname | Select-Object -First 1 $this.Surname = $Found.properties.sn | Select-Object -First 1 $this.Email = $Found.properties.mail | Select-Object -First 1 $this.PasswordNeverExpires = [bool]($Found.userAccountControl -band $DONT_EXPIRE_PASSWORD) $this.PasswordNotRequired = [bool]($Found.userAccountControl -band $ADS_UF_PASSWD_NOTREQD) $this.DistinguishedName = $Found.properties.distinguishedname | Select-Object -First 1 $this.UserPrincipalName = $Found.properties.userprincipalname | Select-Object -First 1 $this.ObjectGUID = New-Object GUID(,($Found.properties.objectguid | Select-Object -First 1)) $this.ObjectSID = (New-Object System.Security.Principal.SecurityIdentifier(($Found.properties.objectsid | Select-Object -First 1),0)).Value $this.MemberOf = $Found.properties.memberof $this.Manager = $Found.properties.manager | Select-Object -First 1 $this.LockedOut = (($Found.properties.lockouttime | Select-Object -First 1) -gt 0) $this.BadPasswordCount = $Found.properties.badpwdcount | Select-Object -First 1 $this.PasswordExpired = [bool]($Found.userAccountControl -band $PASSWORD_EXPIRED) $this.PasswordLastSet = [DateTime]::FromFileTime(($Found.properties.pwdlastset | Select-Object -First 1)) } hidden [PSCustomObject] GetGroupNames () { $Results = ForEach ($Member in $this.MemberOf) { $Searcher = [ADSISearcher]"(distinguishedName=$Member)" $Found = $Searcher.FindOne() [PSCustomObject]@{ Name = $Found.properties.name | Select-Object -First 1 SamAccountName = $Found.properties.samaccountname | Select-Object -First 1 distinguishedName = $Found.properties.distinguishedname | Select-Object -First 1 } } Return $Results } hidden [void] AddUserToGroup ( [string]$DN ) { $Searcher = [ADSISearcher]"(distinguishedName=$DN)" $Found = $Searcher.FindOne() If ($this.MemberOf -contains $DN) { Write-Error "User is already a member of group ""$($Found.properties.name)""" -ErrorAction Stop } Else { $GroupObj = [ADSI]"LDAP://$($Found.properties.distinguishedname)" $GroupObj.Add("LDAP://$($this.distinguishedName)") Write-Verbose "Added to Group ""$($Found.properties.name)"", will take a minute to show up in `$SAUser" -Verbose } } hidden [PSCustomObject] Get4740Events ( [datetime]$Start, [datetime]$End ) { $PDCEmulator = Get-SADomainController | Where-Object Roles -Contains "PdcRole" | Select-Object -ExpandProperty Name Write-Verbose "PDC Emulator: $PDCEmulator" -Verbose $FilterHash = @{ LogName = "Security" StartTime = $Start EndTime = $End ID = 4740 } $Results = $null Write-Verbose "Searching (be patient)..." -Verbose Try { $Results = Get-WinEvent -ComputerName $PDCEmulator -FilterHashtable $FilterHash -ErrorAction Stop | Where-Object Message -Like "*$($this.SamAccountName)*" | Select-Object TimeCreated, @{Name="User";Expression={$Username}}, @{Name="LockedOn";Expression={$PSItem.Properties.Value[1]}}, @{Name="DC";Expression={$PDCEmulator}} } Catch { Write-Error "Unable to retrieve event log for $PDCEmulator because ""$_""" -ErrorAction Stop } Return $Results } [void] Unlock () { $Found = [ADSI]"LDAP://$($this.DistinguishedName)" $Found.Put("lockouttime",0) $Found.SetInfo() } [PSCustomObject[]] GetGroups () { $Groups = $this.GetGroupNames() | Sort-Object Return $Groups } [PSCustomObject[]] GetGroups ( [string]$Filter ) { $Groups = $this.GetGroupNames() | Where-Object Name -match $Filter | Sort-Object Return $Groups } [void] RemoveGroup ( [string]$GroupName ) { $Searcher = [ADSISearcher]"(&(objectCategory=group)(samAccountName=$GroupName))" $Found = $Searcher.FindOne() If ($null -eq $Found.properties.samaccountname) { Write-Error "Unable to locate group ""$GroupName""" -ErrorAction Stop } Else { If ($this.MemberOf -contains $Found.properties.distinguishedname) { $GroupObj = [ADSI]"LDAP://$($Found.properties.distinguishedname)" $GroupObj.Remove("LDAP://$($this.DistinguishedName)") Write-Verbose "Removed from group ""$($Found.properties.name)""" -Verbose } Else { Write-Error "User is not currently a member of ""$GroupName""" -ErrorAction Stop } } } [void] AddGroup ( [string]$GroupName ) { $Searcher = [ADSISearcher]"(&(objectCategory=group)(objectClass=group)(samAccountName=*$GroupName*))" $Searcher.PageSize = 1000 $Found = $Searcher.FindAll() If (@($Found).Count -gt 1) { $Selected = $Found | Select-Object @{Name="SamAccountName";Expression={ $_.properties.samaccountname }}, @{Name="DisplayName";Expression={ $_.properties.displayname }}, @{Name="DistinguishedName";Expression={ $_.properties.distinguishedname }} | Out-GridView -Title "Select the groups to add" -OutputMode Multiple If (@($Selected).Count -ge 1) { $Found = ForEach ($Group in $Selected) { $this.AddUserToGroup($Group.DistinguishedName) } } Else { Write-Warning "No group selected" Return } } ElseIf (@($Found).Count -eq 0) { Write-Warning "No group matching ""*$GroupName*"" found" Return } Else { $this.AddUserToGroup($Found.properties.distinguishedname) } } [void] ResetPassword () { $Password1 = Get-Credential -UserName $this.SamAccountName -Message "Enter new password" $Password2 = Get-Credential -UserName $this.SamAccountName -Message "Verify new password" If ($Password1.GetNetworkCredential().Password -ceq $Password2.GetNetworkCredential().Password) { $UserObj = [ADSI]"LDAP://$($this.distinguishedName)" $UserObj.SetPassword($Password1.GetNetworkCredential().Password) } Else { Write-Error "Passwords did not match" -ErrorAction Stop } } [void] GetLastLogon () { $DCs = Get-SADomainController | Select-Object -ExpandProperty Name $Count = 1 $DCData = ForEach ($DC in $DCs) { Write-Progress -Activity "Retrieving user data from Domain Controllers" -Status "...$DC ($Count of $($DCs.Count))" -Id 0 -PercentComplete ($Count * 100 / $DCs.Count) $UserObj = [ADSI]"LDAP://$DC/$($this.distinguishedName)" If ($null -ne ($UserObj.lastlogon | Select-Object -First 1)) { [datetime]::FromFileTime($UserObj.ConvertLargeIntegerToInt64(($UserObj.lastLogon | Select-Object -First 1))) } $Count ++ } Write-Progress -Activity " " -Status " " -Completed $this.LastLogon = ($DCData | Sort-Object -Descending | Select-Object -First 1).ToString() Write-Verbose "Last Logon for $($this.Name) was $($this.LastLogon)" -Verbose } [PSCustomObject] FindLockout () { $Start = (Get-Date).AddDays(-2) $End = Get-Date $Results = $this.Get4740Events($Start, $End) Return $Results } [PSCustomObject] FindLockout ( [datetime]$Start ) { $End = Get-Date $Results = $this.Get4740Events($Start, $End) Return $Results } [PSCustomObject] FindLockout ( [datetime]$Start, [datetime]$End) { $Results = $this.Get4740Events($Start, $End) Return $Results } } Function Get-SADomain { <# .SYNOPSIS Retrieve domain information include site details .EXAMPLE Get-SADomain .NOTES Author: Martin Pugh Twitter: @thesurlyadm1n Spiceworks: Martin9700 Blog: www.thesurlyadmin.com Changelog: 05/27/19 Initial Release .LINK https://github.com/martin9700/SimpleADAdmin #> [CmdletBinding()] Param () Begin { Write-Verbose "$(Get-Date): Get-SADomain beginning" $SelectProperties = "Name","Forest","Parent","Children","DomainMode","DomainModeLevel","DomainControllers","PdcRoleOwner","RidRoleOwner","InfrastructureRoleOwner","Sites" } Process { $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $AllSites = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites $Domain | Add-Member -MemberType NoteProperty -Name Sites -Value $AllSites Write-Output $Domain | Select-Object $SelectProperties } End { Write-Verbose "$(Get-Date): Get-SADomain completed" } } Function Get-SADomainController { <# .SYNOPSIS Get a list of domain controllers .DESCRIPTION Will provide a list of domain controllers in your current domain. Optionally you can also request a discovery of the "closest" one. .PARAMETER ComputerName Retrieve information about the specified domain controller. This is a RegEx match so you can match multiple domain controllers with your pattern. .PARAMETER Discover Use Discover to return the information of the closest domain controller. .EXAMPLE Get-SADomainController Retrieve a list of all domain controllers in your domain. .EXAMPLE Get-SADomainController -Computer 01 Retrieve a list of all domain controlelrs with "01" in their name. .EXAMPLE Get-SADomainController -Discover Retrieve the name of the closest domain controller. .NOTES Author: Martin Pugh Twitter: @thesurlyadm1n Spiceworks: Martin9700 Blog: www.thesurlyadmin.com Changelog: 05/27/19 Initial Release .LINK https://github.com/martin9700/SimpleADAdmin #> [CmdletBinding(DefaultParameterSetName="all")] Param ( [Parameter(Position=0,ParameterSetName="dc")] [string]$ComputerName, [Parameter(ParameterSetName="all")] [switch]$Discover ) Begin { Write-Verbose "$(Get-Date): Get-SADomainController beginning" $DirectoryContext = [System.DirectoryServices.ActiveDirectory.DirectoryContext]::New("Domain") $SelectProperties = "Name","Forest","Domain","SiteName","Roles","CurrentTime","HighestCommittedUsn","OSVersion" } Process { If ($Discover) { $LocatorFlag = [System.DirectoryServices.ActiveDirectory.LocatorOptions]::ForceRediscovery [System.DirectoryServices.ActiveDirectory.DomainController]::FindOne($DirectoryContext, $LocatorFlag) | Select-Object $SelectProperties } ElseIf ($ComputerName) { [System.DirectoryServices.ActiveDirectory.DomainController]::FindAll($DirectoryContext) | Where-Object Name -match $ComputerName | Select-Object $SelectProperties } Else { [System.DirectoryServices.ActiveDirectory.DomainController]::FindAll($DirectoryContext) | Select-Object $SelectProperties } } End { Write-Verbose "$(Get-Date): Get-SADomainController completed" } } Function Get-SAGroup { <# .SYNOPSIS Simple function that will allow you to do the most common group administrative tasks from a single place. .DESCRIPTION This is a more advanced version of Get-ADGroup. It allows you to see administratively useful fields in the default view, but also saves the user object in a global variable: $SAGroup The advantage of this is if you want to do something to the object it's now persistent in your session. All properties on $SAGroup are dynamic, meaning they will update from Active Directory every time you display the variable, which means you don't have to keep rerunning Get-SAGroup after you've made a change in order to see it. Thee are several methods available on $SAUser for an administrator to use, they are: GetMembers Usage: $SAUser.GetMembers() Description: Shows every user and group who is a member of the group. Overload: None GetMembersRecursive Usage: $SAUser.GetMembersRecursive() Description: Shows every user who is a member of the group, even if they are part of a group that's assigned to this one. Overload: None AddMember Usage: $SAUser.AddMember(SamAccountName) Description: Add the designated user to the group Overload: SamAccountName for the user you want to add RemoveMember Usage: $SAUser.RemoveMember(SamAccountName) Description: Remove the designated user to the group Overload: SamAccountName for the user you want to remove .PARAMETER Identity Name of the group you want to interact with. If the group cannot be found, it will attempt to look for groups with a like name and give you the option of selecting one of those. .EXAMPLE Get-SAGroup "Test-Group" Name : Test Group SamAccountName : Test-Group Description : Distribution list for internal tests only Info : Email : test-group@gmail.com DistinguishedName : CN=test-group,OU=Internal,OU=Distribution Lists,DC=surlyadmin,DC=com ObjectGUID : d2fe1397-40bb-48c6-8bf7-5f5c80e127b1 ObjectSID : S-1-5-21-1991516528-409794927-3010460085-114238 MemberOf : Members : {CN=surlyadmins,OU=Internal,OU=Distribution Lists,DC=surlyadmin,DC=com} ManagedBy : CN=Martin Pugh,OU=Employees,DC=surlyadmin,DC=com GroupCategory : Distribution GroupScope : Universal WhenCreated : 2/7/2018 1:46:52 PM LastModified : 9/6/2018 6:04:46 PM .NOTES Author: Martin Pugh Twitter: @thesurlyadm1n Spiceworks: Martin9700 Blog: www.thesurlyadmin.com Changelog: 05/25/19 Initial Release .LINK https://github.com/martin9700/SimpleADAdmin #> [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position = 0)] [Alias("Group","SamAccountName","Name")] [string]$Identity ) # Clear old variable (if present) Remove-Variable -Name SAGroup -Scope Global -ErrorAction SilentlyContinue # Find the group $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$Identity))" $Found = @($Searcher.FindAll()) If ($Found.Count -ne 1) { If ($Found.Count -eq 0) { Write-Verbose "No user matching ""$Identity"", trying for a match" $Searcher = [ADSISearcher]"(&(objectClass=group)(name=*$Identity*))" $Found = @($Searcher.FindAll()) } If ($Found.Count -gt 1) { # Found more than one, need to select which one you want $Selected = $Found | Select-Object @{Name="SamAccountName";Expression={ $_.properties.samaccountname }}, @{Name="DisplayName";Expression={ $_.properties.displayname }}, @{Name="Description";Expression={ $_.properties.description }} | Sort-Object -Property SamAccountName | Out-GridView -Title "Select the correct group" -PassThru If (@($Selected).Count -eq 0) { Write-Warning "No group selected" Return } $Searcher = [ADSISearcher]"(&(objectClass=group)(samAccountName=$($Selected.SamAccountName)))" $Found = $Searcher.FindOne() } ElseIf ($Found.Count -eq 0) { Write-Error "Unable to locate group matching *$Identity*" -ErrorAction Stop } } # Set global variable and return object $Global:SAGroup = [SAGroup]::New($Found.properties.samaccountname) Return $Global:SAGroup } Function Get-SAUser { <# .SYNOPSIS Simple function that will allow you to do the most common user administrative tasks from a single place. .DESCRIPTION This is a more advanced version of Get-ADUser. It allows you to see administratively useful fields in the default view, but also saves the user object in a global variable: $SAUser The advantage of this is if you want to do something to the object it's now persistent in your session. All properties on $SAUser are dynamic, meaning they will update from Active Directory every time you display the variable. This means you don't have to keep rerunning Get-SAUser after you've made a change in order to see it. Thee are several methods available on $SAUser for an administrator to use, they are: AddGroup Usage: $SAUser.AddGroup("NameOfGroup") Description: Add the user to a group. Overload: You can add the name of a group in the overload and the function will find all groups that match that name pattern and let you select which group or groups you want to add. If you give an exact match it will just add it without prompting. FindLockout Usage: $SAUser.FindLockedout() Description: Will go to the PDC emulator and look for event ID 4740 (lockout) in the Security Event Log. Overload: None GetGroups Usage: $SAUser.GetGroups() Description: The "MemberOf" field will always show what groups the user is in, but it's the FQDN. Use the GetGroups() method to see just their Name. Overload: You can add an overload to filter the result: $SAUser.GetGroups("test") GetLastLogon Usage: $SAUser.GetLastLogon() Description: Will go out to all domain controllers in your domain and locate the latest logon for the user. Overload: None RemoveGroup Usage: $SAUser.RemoveGroup("NameOfGroup") Description: Remove the user from the specified group. Overload: Name of the group, or closest match. If you specify the exact name, or the filter data you provide only has one match thenthe user will be removed from the group without prompt. If there are more then one match you will be asked to select the group or groups you want to remove. ResetPassword Usage: $SAUser.ResetPassword() Description: Method will then prompt for new password Overload: None Unlock Usage: $SAUser.Unlock() Description: Will unlock the user account Overload: None .PARAMETER User Full SamAccountName, or partial name of the user. If partial all users that match will be shown in a window and you can select the one you want .INPUTS None .OUTPUTS $SAUser PSCustomObject .EXAMPLE Get-SAUser mpugh $SAUser.Unlock() Get user information for mpugh, see that the account is locked. Use the Unlock() method to unlock the account. .EXAMPLE Get-SAUser Martin Shows a large list of users. Select Martin Pugh .NOTES Author: Martin Pugh Date: 8/11/2016 Changelog: 08/11/16 MLP - MVP (minimum viable product) release with Readme.md and updated help 05/26/19 MLP - Converted to using class .LINK https://github.com/martin9700/SimpleADAdmin #> [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [Alias("User","UserName","SamAccountName","Name")] [string]$Identity ) $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$Identity))" $Found = $Searcher.FindOne() If ($Found.Count -eq 0) { Write-Verbose "No user matching $SAUser, trying for a match" $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(displayName=*$Identity*))" $Found = $Searcher.FindAll() If (@($Found).Count -gt 1) { #Found more than one, need to select which one you want $Selected = $Found | Select-Object @{Name="SamAccountName";Expression={ $_.properties.samaccountname }}, @{Name="DisplayName";Expression={ $_.properties.displayname }} | Out-GridView -Title "Select the user you want" -PassThru If (@($Selected).Count -eq 0) { Write-Warning "No user selected" Return } $Searcher = [ADSISearcher]"(&(objectCategory=person)(objectClass=user)(samAccountName=$($Selected.SamAccountName)))" $Found = $Searcher.FindOne() } If (@($Found).Count -eq 0) { Write-Error "No user found, exiting" -ErrorAction Stop } } #Create the object $Global:SAUser = [SAUser]::New($Found.properties.samaccountname) #Display it $Global:SAUser } |