ActiveDirectory.psm1
#region Test-ActiveDirectoryGroupMemebership Function Test-ActiveDirectoryGroupMembership { <# .SYNOPSIS Test if a user is a member of a group. .DESCRIPTION Test if a user is member of a security group. .PARAMETER User The username of the user. .PARAMETER Group The name of the group. .EXAMPLE Test-ADNestedGroupMembership myuser mygroup #> Param ( [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Username", "SamAccountName")] [string[]]$User, [Parameter(Mandatory=$True,Position=2)] [Alias("Groupname")] [string]$Group, [switch]$Recurse ) Begin {} Process { # Loop through the users Foreach($u in $User) { # Create a custom object $obj = New-Object psobject $obj | Add-Member -MemberType NoteProperty -Name User -Value $u $obj | Add-Member -MemberType NoteProperty -Name Group -Value $Group # Test if the user exists try { $aduser = Get-ADUser $u -ErrorAction Stop } catch { Write-Error "Could not find user $u" continue } # Test if the group exists try { $adgroup = Get-ADGroup $Group -ErrorAction Stop } catch { Throw "Could not find group $Group" } $obj | Add-Member NoteProperty "User DN" $aduser.DistinguishedName $obj | Add-Member NoteProperty "Group DN" $adgroup.DistinguishedName if($Recurse) { # Recursive query if( Get-ADUser ` -Filter "memberOf -RecursiveMatch '$($adgroup.DistinguishedName)'" ` -SearchBase $($aduser.DistinguishedName) ) { $obj | Add-Member -MemberType NoteProperty -Name Member -Value $True } else { $obj | Add-Member -MemberType NoteProperty -Name Member -Value $false } } else { # Direct member query if( Get-ADUser ` -Filter {memberof -eq $adGroup.DistinguishedName -and distinguishedname -eq $aduser.DistinguishedName} ) { $obj | Add-Member -MemberType NoteProperty -Name Member -Value $True } else { $obj | Add-Member -MemberType NoteProperty -Name Member -Value $false } } $obj } } End {} } #endregion #region Test-ActiveDirectoryIsDomainAdmin Function Test-ActiveDirectoryIsDomainAdmin { <# .SYNOPSIS Test if a user has domain administrator privileges. .DESCRIPTION Test if a user is member of the Domain Admins security group including nested groups. .PARAMETER Username The username of the user. .EXAMPLE Test-ADIsDomainAdmin myuser This will return true if the user is a member of the Domain Admins group or false if not. #> Param ( [Parameter( Mandatory=$True, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true) ] [alias("Username")] [string[]]$User ) Begin {} Process { Foreach($u in $User) { # Get the user try { $aduser = Get-ADUser $u -ErrorAction Stop -Properties SamAccountName } catch { Write-Error "Could not find user $u." } Test-ActiveDirectoryGroupMembership -User $aduser.SamAccountName -Group "Domain Admins" -Recurse } } End {} } #endregion #region Get-ActiveDirectoryUserGroupMembershipHistory Function Get-ActiveDirectoryUserGroupMembershipHistory { <# .SYNOPSIS Get the group membership history of an account .DESCRIPTION Get the addition history of a user regarding security groups. This cmdlet only displays the groups that the user is member of and only the date when the user was originaly added. .PARAMETER Username The username of the user. .PARAMETER Group The name of the group .EXAMPLE Get-ADUserGroupMembershipHistory -Username myuser -Group mygroup This will return the memberhip additions of the myuser group to and from the mygroup group. #> Param ( [Parameter(Mandatory=$True,Position=0)] [string]$Username, [Parameter(Mandatory=$False,Position=1)] [string]$Group, [Parameter(Mandatory = $False, Position = 2)] [string]$Server = $env:COMPUTERNAME ) # Get the user from Active Directory try { $userobj = Get-ADUser $username -ErrorAction Stop } catch { Throw "Could not find user $Username." } $results = Get-ADUser $userobj.DistinguishedName -Server $Server -Properties memberOf | Select-Object -ExpandProperty memberOf | ForEach-Object { Get-ADReplicationAttributeMetadata $_ -Server $Server -ShowAllLinkedValues | Where-Object {` $_.AttributeName -eq 'member' -and $_.AttributeValue -eq $userobj.DistinguishedName} | Select-Object -Property ` @{name="OriginallyAdded";Expression={$_.FirstOriginatingCreateTime}}, ` @{name="User";Expression={$username}}, ` @{name="Group";Expression={(Get-ADObject -Identity $_.object).Name}}, ` @{name="UserDN";Expression={$_.AttributeValue}}, ` @{name="GroupDN";Expression={$_.Object}} } # Narrow down th if( $group ) { # Get the group try { $adgroup = Get-AdGroup $Group -ErrorAction Stop -Server $Server } catch { Throw "Could not find group $group." } # Filter the results $results | Where-Object {$_.groupdn -eq $adgroup.distinguishedname} } else { $results } } #endregion #region Get-ActiveDirectoryAccountLockEvent Function Get-ActiveDirectoryAccountLockEvent { <# .Synopsis Get the account lock events. .DESCRIPTION Get the account lock events from the security event log of the domain controllers. .EXAMPLE Get-ActiveDirectoryAccountLockEvent -StartTime $start Account Timestamp Domain Controller Caller Computer ------- --------- ----------------- --------------- cpolydorou 27/5/2017 7:44:43 μμ DC3 WINDOWS10 cpolydorou 27/5/2017 7:44:43 μμ DC1 WINDOWS10 #> [CmdletBinding()] Param ( # The starting date [Parameter(Mandatory=$false, Position=0)] [DateTime] $StartTime ) # Form the event log query $now = [DateTime]::Now # If the start time has not been specified, we'll search for events in last hour if(-Not $StartTime) { $StartTime = $now.AddHours(-1) } $timespan = $now - $StartTime $query = @" <QueryList> <Query Id="0" Path="Security"> <Select Path="Security">*[System[(EventID=4740) and TimeCreated[timediff(@SystemTime) <= $($timespan.TotalMilliseconds)]]]</Select> </Query> </QueryList> "@ # Import the ActiveDirectory module Write-Verbose "Getting Domain Controllers" try { $domainControllers = Get-ADDomainController -Filter * -ErrorAction Stop | % Name } catch { throw "Could not get the Domain Controllers." } # Get the events from all domain controllers Write-Verbose "Getting events" $events = # Search for the relative events on the domain controllers Invoke-Command -ComputerName $domainControllers ` -ScriptBlock { Param( $q ) try { Get-WinEvent -FilterXml $q -ErrorAction Stop } catch { if($_.Exception.Message.StartsWith("No events were found")) { return $null } else { throw $_.Exception } } } -ArgumentList $query # Process the events Write-Verbose "Processing events" foreach($e in $events) { if($e -ne $null) { # Get the account that was locked out $startIndex = $e.Message.IndexOf("Account That Was Locked Out:") + 28 $account = $e.message.substring($startIndex, $e.message.length - $startIndex) $startIndex = $account.IndexOf("Account Name:") + 13 $account = $account.Substring($startIndex, $account.length - $startIndex) $endIndex = $account.IndexOf("`r") $account = $account.substring(0, $endIndex).Trim() # Get the caller computer $start = $e.Message.IndexOf("Caller Computer Name") + 21 $caller = $e.message.substring($start, $e.message.length - $start).Trim() # Create a custom object $obj = New-Object psobject -Property @{ "Timestamp" = $e.TimeCreated "Account" = $account "Caller Computer" = $caller "Domain Controller" = $e.PSComputerName } $obj } } } #endregion #region Compare-ActiveDirectoryObject Function Compare-ActiveDirectoryObject { <# .Synopsis Compare two Active Directory objects. .DESCRIPTION Compare two Active Directory objects. .EXAMPLE PS C:\> $ADObject1 = Get-ADUser cpolydorou -Properties * PS C:\> $ADObject2 = Get-ADUser administrator -Properties * PS C:\> Compare-ActiveDirectoryObject -ReferenceObject $ADObject1 -DifferenceObject $ADObject2 | Select-Object -First 10 PropertyName ReferenceValue DifferenceValue Status ------------ -------------- --------------- ------ AccountExpirationDate Equal accountExpires 9223372036854775807 0 Different AccountLockoutTime 27/5/2017 7:44:43 μμ Different AccountNotDelegated False False Equal adminCount 1 1 Equal AllowReversiblePasswordEncryption False False Equal AuthenticationPolicy {} {} Equal AuthenticationPolicySilo {} {} Equal BadLogonCount 3 0 Different badPasswordTime 131403770838829365 131415008228411927 Different Get two users from Active Directory and compare all their properties (The first 10 have been selected). .EXAMPLE PS C:\> Compare-ActiveDirectoryObject -ReferenceObject $ADObject1 -DifferenceObject $ADObject2 -Properties SamAccountName,UserPrincipalName PropertyName ReferenceValue DifferenceValue Status ------------ -------------- --------------- ------ SamAccountName cpolydorou Administrator Different UserPrincipalName cpolydorou@LAB.local Administrator@LAB.local Different Compare only the properties SamAccountName and UserPrincipalName of the objects from the previous example. #> [cmdletBinding()] Param( # The reference object [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [PSObject] $ReferenceObject, # The difference object [Parameter(Mandatory=$true, Position=1)] [ValidateNotNullOrEmpty()] [PSObject] $DifferenceObject, # The difference object [Parameter(Mandatory=$false, Position=2)] [string[]]$Properties ) # If a list of properties has not been provided, use all the properties of the objects if(-not $Properties) { # Get the names of the properties of the reference object $Properties = $ReferenceObject | Get-Member -MemberType Property,NoteProperty | % Name # Get the names of the properties of the difference object $Properties += $DifferenceObject | Get-Member -MemberType Property,NoteProperty | % Name # Select the unique values $Properties = $Properties | Sort-Object | Select-Object -Unique } # Loop through each property foreach ($property in $Properties) { # Compare the property between the objects $diff = Compare-Object $ReferenceObject $DifferenceObject -Property $property if ($diff) { # There is a difference $props = [ordered]@{ "PropertyName" = $property "ReferenceValue" = ($diff | ? {$_.SideIndicator -eq ‘<='} | % $($property)) "DifferenceValue" = ($diff | ? {$_.SideIndicator -eq ‘=>’} | % $($property)) "Status" = "Different" } } else { # The properies are equal $props = [ordered]@{ "PropertyName" = $property "ReferenceValue" = $ReferenceObject.($property) "DifferenceValue" = $DifferenceObject.($property) "Status" = "Equal" } } # Create a custom object New-Object PSObject -Property $props } } #endregion #region Get-ActiveDirectoryGroupMember function Get-ActiveDirectoryGroupMember { <# .Synopsis Get the members of an Active Directory group. .DESCRIPTION Get the members of an Active Directory group. .EXAMPLE PS C:\> Get-ActiveDirectoryGroupMember -Identity "Domain Admins" -Recurse DistinguishedName Name ObjectClass ObjectGUID ----------------- ---- ----------- ---------- CN=InfrastructureAdmins,OU=SecurityGroups,DC=lab,DC=local InfrastructureAdmins group 08ee2512-4ad1-4f60-8bca-5153cddccc47 CN=Administrator,CN=Users,DC=lab,DC=local Administrator user 32ebb121-b479-4bab-8c1c-9e96997e2834 .EXAMPLE PS C:\> Get-ADGroup "Domain Admins" | Get-ActiveDirectoryGroupMember -Recurse DistinguishedName Name ObjectClass ObjectGUID ----------------- ---- ----------- ---------- CN=InfrastructureAdmins,OU=SecurityGroups,DC=lab,DC=local InfrastructureAdmins group 08ee2512-4ad1-4f60-8bca-5153cddccc47 CN=Administrator,CN=Users,DC=lab,DC=local Administrator user 32ebb121-b479-4bab-8c1c-9e96997e2834 #> [CmdletBinding(PositionalBinding=$false)] Param ( # The group [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0)] [string] $Identity, # Recursive query [Parameter()] [switch] $Recurse, # The server [Parameter(Mandatory=$false, Position=1)] [string] $Server ) Begin { #region Load the Active Directory module try { Import-Module ActiveDirectory -ErrorAction Stop } catch { Throw "Could not load the 'ActiveDirectory' module." } #endregion } Process { #region Get the group $group = Get-ADGroup $Identity -ErrorAction Stop #endregion # The parameters for the command $params = @('-ResultSetSize', '$null') #region Set the query type (one level - recursive) if($Recurse) { $params += "-Filter" $params += "`"(memberOf -RecursiveMatch '$($group.DistinguishedName)')`"" } else { $params += "-LDAPFilter" $params += "`"(memberof=$($group.distinguishedname))`"" } #endregion #region Set the server if($Server) { $params += "-Server" $params += $Server } #endregion #region Execute the command $sb = [scriptblock]::Create("Get-ADObject " + $params) Invoke-Command -ScriptBlock $sb #endregion } End { } } #endregion #region Get-ActiveDirectoryEmailAddress function Get-ActiveDirectoryEmailAddress { <# .Synopsis Get the SMTP addresses using Active Directory. .DESCRIPTION Get the SMTP addresses of an Active Directory object using .NET. .EXAMPLE PS C:\> Get-ActiveDirectoryEmailAddress -SamAccountName cpolydorou DistinguishedName : CN=Christos Polydorou,CN=Users,DC=LAB,DC=LOCAL SamAccountName : cpolydorou UserPrincipalName : cpolydorou@lab.local SMTPAddresses : {cpolydorou@lab.local, cp@lab.local} PrimarySMTPAddress : cpolydorou@lab.local Get the SMTP Addresses of the user with SamAccountName "cpolydorou" #> [CmdletBinding(DefaultParameterSetName='UserPrincipalName')] Param ( # Query using UserPrincipalName [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0, ParameterSetName='UserPrincipalName')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] $UserPrincipalName, # Query using SamAccountname [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0, ParameterSetName='SamAccountName')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] $SamAccountName, # Query using DistinguishedName [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0, ParameterSetName='DistinguishedName')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] $DistinguishedName ) Begin { # Prepare the Active Directory searcher $objDomain = New-Object System.DirectoryServices.DirectoryEntry $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1 } Process { # Form the query if($UserPrincipalName) { $query = "((userprincipalname=$UserPrincipalName))" } if($SamAccountName) { $query = "((samaccountname=$SamAccountName))" } if($DistinguishedName) { $query = "((DistinguishedName=$DistinguishedName))" } # Get the Active Directory object $objSearcher.Filter = $query $objSearcher.SearchScope = "Subtree" $colProplist = "DistinguishedName", "SamAccountName", "UserPrincipalName", "ProxyAddresses" foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | Out-Null } $colResults = $objSearcher.FindOne() # TODO: Test result if($colResults -eq $null) { Write-Error "Could not find a user." return } if($colResults.Properties["proxyaddresses"] -ne $null) { $smtpAddresses = New-Object System.Collections.ArrayList foreach($a in $colResults.Properties["proxyaddresses"]) { if($a.tolower().startswith("smtp:")) { $smtpAddresses.Add($a.split(":")[1]) | Out-Null if($a.startswith("SMTP:")) { $primarySMTPAddress = $a.split(":")[1] } } } } # Create a custom object $properties = [ordered]@{ "DistinguishedName" = $colResults.Properties["DistinguishedName"][0] "SamAccountName" = $colResults.Properties["SamAccountName"][0] "UserPrincipalName" = $colResults.Properties["UserPrincipalName"][0] "SMTPAddresses" = $smtpAddresses "PrimarySMTPAddress" = $primarySMTPAddress } New-Object -TypeName psobject -Property $properties } End { # Clean up $objSearcher.Dispose() } } #endregion #region Get-ActiveDirectoryGroupMembership function Get-ActiveDirectoryGroupMembership { <# .Synopsis Get the groups an Active Directory object is a member of. .DESCRIPTION Get the groups an Active Directory object is a member of having the option to include all the groups (including groups that are nested). .EXAMPLE PS C:\> Get-ActiveDirectoryGroupMembership -Identity "CN=Christos Polydorou,CN=Users,DC=lab,DC=local" DistinguishedName GroupCategory GroupScope Name ObjectClass ObjectGUID SamAccountName SID ----------------- ------------- ---------- ---- ----------- ---------- -------------- --- CN=Test Group 1 Nested,OU=Tes... Security Global Test Group 1 Nested group 326195ba-2d8b-40f0-8a39-1c08... Test Group 1 Nested S-1-5-21-3554682577-58629175... The user is a direct member of the group "Test Group 1 Nested" only. .EXAMPLE PS C:\> Get-ActiveDirectoryGroupMembership -Identity "CN=Christos Polydorou,CN=Users,DC=lab,DC=local" -Recurse DistinguishedName GroupCategory GroupScope Name ObjectClass ObjectGUID SamAccountName SID ----------------- ------------- ---------- ---- ----------- ---------- -------------- --- CN=Test Group 1 Parent,OU=Tes... Security Global Test Group 1 Parent group d19916ff-106a-49c4-9aa6-78fa... Test Group 1 Parent S-1-5-21-3554682577-58629175... CN=Test Group 1,OU=Test_OU,DC... Security Global Test Group 1 group 9c11c15f-d4e5-4afe-9f1a-06db... Test Group 1 S-1-5-21-3554682577-58629175... CN=Test Group 1 Nested,OU=Tes... Security Global Test Group 1 Nested group 326195ba-2d8b-40f0-8a39-1c08... Test Group 1 Nested S-1-5-21-3554682577-58629175... The user is a direct member of the group "Test Group 1 Nested" only. The "Test Group 1 Nested" is a member of "Test Group 1" which in turn is a member of "Test Group 1 Parent". Thus the user is concidered a member of all groups #> [CmdletBinding(PositionalBinding=$false)] Param ( # The object to check it's membership [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0)] [string] $Identity, # Recursive query [Parameter()] [switch] $Recurse ) Begin { #region Load the Active Directory module try { Import-Module ActiveDirectory -ErrorAction Stop } catch { Throw "Could not load the 'ActiveDirectory' module." } #endregion #region __GetNestedGroups function __GetParentGroups { # Get the parent groups of a group Param ( $DN ) if(-Not $alreadyExaminedGroups.Contains($DN)) { # Get the Active Directory group object $parent = Get-ADObject -LDAPFilter "(member=$DN)" ` -ResultSetSize $null | %{ Get-ADGroup $_.Distinguishedname } # Return the group $parent # Add the group to the list of already examined groups # in order to avoid infinate loops $alreadyExaminedGroups.Add($DN) | Out-Null # Process the next level foreach($p in $parent) { # Process the group __GetParentGroups -DN $p.DistinguishedName } } } #endregion } Process { #region Get the object $object = Get-ADObject -Identity $Identity ` -Properties MemberOf ` -ErrorAction Stop #endregion #region Save examined groups # This variable is used in order to avoid infinate loops # since many paths may lead to the same group $alreadyExaminedGroups = New-Object System.Collections.ArrayList #endregion #region Get the groups the object is member of $groups = $object | % MemberOf #endregion #region Get the groups if($Recurse) { # The variable to hold the result $result = New-Object System.Collections.ArrayList #region Get the Active Directory groups that are parents of the objects groups $groups | %{ __GetParentGroups -DN $_ } | %{ # Add each member to the list of groups $result.Add($_) | Out-Null } #endregion #region Get the Active Directory groups the object is a member of $groups | %{ # Add each member to the list of groups $result.Add((Get-ADGroup $_)) | Out-Null } #endregion # Return the result without duplicates $result | Select-Object -Unique } else { #region Get the Active Directory groups the object is a member of $groups | %{ Get-ADGroup $_ } #endregion } #endregion } End { } } #endregion #region Get-ActiveDirectoryComputerAccountCreator function Get-ActiveDirectoryComputerAccountCreator { #region Parameters [CmdletBinding(PositionalBinding=$false)] [Alias()] [OutputType([String])] Param ( # The name of the computer [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0)] [ValidateNotNullOrEmpty()] [string[]] $ComputerName, # The Domain Controller to use [string] $Server ) #endregion #region Begin Begin { # Check if the Active Directory module is installed/loaded if((Get-Module | % Name) -notcontains "ActiveDirectory") { Write-Verbose "Importing the 'ActiveDirectory' module." try { Import-Module -Name "ActiveDirectory" -ErrorAction Stop -Verbose:$false } catch { Throw ("Failed to load the 'Active Directory' module. " + $_.Exception.Message) } } } #endregion #region Process Process { foreach($c in $ComputerName) { # Get the computer object Write-Verbose "Searching for a computer object named ""$c""..." try { if($Server) { $computerObject = Get-ADComputer -Filter {Name -eq $c} -Properties "mS-DS-CreatorSID" -Server $Server -ErrorAction Stop } else { $computerObject = Get-ADComputer -Filter {Name -eq $c} -Properties "mS-DS-CreatorSID" -ErrorAction Stop } } catch { Write-Error ("Failed to get a computer object for " + $c + " ." + $_.Exception.Message) continue } if($computerObject -eq $null) { Write-Error ("Failed to find a computer object with name '" + $c + "'.") continue } else { Write-Verbose ("Found object """ + $computerObject.DistinguishedName + """ .") } # Get the object that created the account Write-Verbose "Examining computer object for the creator information..." if([System.String]::IsNullOrEmpty($computerObject.'mS-DS-CreatorSID')) { Write-Warning "Failed to find the creator information on the computer object. The account could have been created by an administrator." continue } try { Write-Verbose "Searching for the object that created the computer account..." if($Server) { $creator = Get-ADObject -LDAPFilter ( "(objectSID=" + $computerObject.'mS-DS-CreatorSID' + ")") -Server $Server -ErrorAction Stop } else { $creator = Get-ADObject -LDAPFilter ( "(objectSID=" + $computerObject.'mS-DS-CreatorSID' + ")") -ErrorAction Stop } } catch { Write-Error ("Failed to get the object that created the computer object " + $c) } # Check if the object exists or not if($creator -eq $null) { Write-Warning ("Failed to find the object " + $computerObject.'mS-DS-CreatorSID' + ". The object may have been removed.") continue } else { # Create a custom object $props = [ordered]@{ Computer = $c ComputerDistinguishedName = $computerObject.DistinguishedName Creator = $creator.Name CreatorDistinguishedName = $creator.DistinguishedName CreatorClass = $creator.ObjectClass } New-Object -TypeName PSObject ` -Property $props } } } #endregion #region End End { } #endregion } #endregion #region Exports Export-ModuleMember -Function Test-ActiveDirectoryGroupMembership Export-ModuleMember -Function Test-ActiveDirectoryIsDomainAdmin Export-ModuleMember -Function Get-ActiveDirectoryUserGroupMembershipHistory Export-ModuleMember -Function Get-ActiveDirectoryAccountLockEvent Export-ModuleMember -Function Compare-ActiveDirectoryObject Export-ModuleMember -Function Get-ActiveDirectoryGroupMember Export-ModuleMember -Function Get-ActiveDirectoryEmailAddress Export-ModuleMember -Function Get-ActiveDirectoryGroupMembership Export-ModuleMember -Function Get-ActiveDirectoryComputerAccountCreator #endregion |