Showing posts with label Active Directory. Show all posts
Showing posts with label Active Directory. Show all posts

27 January 2018

Find FSMO roles from powershell

Get-ADDomainController -Filter * | Select-Object Name, Site,  OperatingSystem, OperationMasterRoles

21 January 2018

Active directory domain user last logon date and time


"lastLogon" attribute is per domain controller - is not replicated to other domain controllers in the domain and each domain cotroller has his own information.

"lastLogonTimeStamp" is replicated in the domain (all domain controllers have the same updated information).

the date is stored in 100 miliseconds interval since 01.01.1601 (Juanuary 1, 1601)

to convert from System.Int64 we can use "FromFileTime" static method of DateTime class:

[System.DateTime]::FromFileTime($ADUser.lastlogon)
[System.DateTime]::FromFileTime($ADUser.lastlogontimestamp)

http://msdn.microsoft.com/en-us/library/ms676824(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms676823(VS.85).aspx



Active Directory Technical Specification


search the web for "MS-ADTS"

https://msdn.microsoft.com/en-us/library/cc223122.aspx


List active directory group membership changes


$ADGroup = Get-ADGroup -Identity 'Domain Admins'
Get-ADReplicationAttributeMetadata -Object $ADGroup.DistinguishedName -Server dc1 -ShowAllLinkedValues

in the output the "AttributeName" is the attribute that was changed - we should search for the "member" attribute.

"AttributeValue" is the value assigned to the attribute.
"FirstOriginatingCreateTime" is the time the value was added.
"LastOriginatingDeleteTime" is the time the value was deleted - but only if is different from "1/1/1601 2:00:00 AM"

01 September 2015

LDAP syntax filters


=
Equality
>=
Greater than or equal to (lexicographical)
<=
Less than or equal to (lexicographical)
&
AND, all conditions must be met
|
OR, any of the conditions must be met
!
NOT, the clause must evaluate to False


all user object filter:  (&(objectCategory=person)(objectClass=user)) 

a more efficient all user object filter: (sAMAccountType=805306368)

21 May 2015

Find available (unique) username in Active Directory

function test{
    for($i=0; $i -le $prenume.Split(' ').Length - 1; $i++){
        for($j=0; $j -le $nume.Split(' ').Length - 1; $j++){
                $TestName = $prenume.Split(' ')[$i].Trim() + '.' + $nume.Split(' ')[$j].Trim()
                if($TestName.Length -gt 20){ $TestName = $TestName.Substring(0,20) }
                $aduser = (Get-ADUser -LDAPFilter "(SamAccountName=$TestName)")
                if(!$aduser){
                    $TestName = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($TestName.ToLower())
                    return $TestName
                }
                Clear-Variable aduser
        }
    }

    # a unique username is was not found - try by appending numbers
    $i = 0
    while(!$aduser){
            $i++
            $TestName = $nume.Split(' ')[0].Trim() + $i + '.' + $prenume.Split(' ')[0].Trim()
            if($TestName.Length -gt 20){ $TestName = $TestName.Substring(0,20) }
            $aduser = (Get-ADUser -LDAPFilter "(SamAccountName=$TestName)")
            if(!$aduser){
                $TestName = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($TestName.ToLower())
                return $TestName
            }
    }
}

31 March 2015

Find domain controller with user replicated

When i'm creating a new user at the same time i'm trying to modify different properties on him like setup a manager, job title, include him in some groups ...and so on.

Sometimes the user is not replicated on all domain controllers in domain fast enough and any command after the New-ADUser will fail (with ADIdentityNotFoundException).

To overcome this problem i created a function that will find a domain controller on witch the user was replicated and used in the next commands as an argument for the Server parameter.


function Find-ReplicatedDC{
    param([string]$UserName)

    $AllDCinDomain = Get-ADDomainController -Filter *

    do{
        foreach( $DC in $AllDCinDomain){
                try{
                    $ADUser = Get-ADUser -Identity $username -Server $DC.HostName
                    $ReplicatedDC = $DC.HostName
                    break
                }
                catch{
                    Start-Sleep -Seconds 1
                }
        }
    }
    while(!$ReplicatedDC)

    return $ReplicatedDC
}

26 January 2015

Active Directory schema attribute details

$schema =[DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema()

$schema.FindClass('user').optionalproperties | Where-Object {$_.name -eq 'employeeid'}

27 October 2014

Verify active directory user and password

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$context = [System.DirectoryServices.AccountManagement.ContextType]::Domain

$principalc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($context, 'local.intra', 'testuser','pass')

$principalc.ConnectedServer

$principalc.ValidateCredentials('testuser','pass')

02 October 2014

Restore active directory object

it only works if:

  • forest functional level is 2008 R2 (only if all domain controllers are running Windows 2008 R2)
  • Active Directory Recycle Bin was enabled before the object was deleted.


Get-ADObject -Filter {samaccountname -like '*marius*'} -IncludeDeletedObjects -Server adc | Restore-ADObject -PassThru

How to filter for null values with Get-ADUser cmdlet


Get-ADUser -Filter {title -notlike "*"}

26 May 2014

System.DirectoryServices.ActiveDirectory Namespace


[ActiveDirectory.Forest]
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().ApplicationPartitions
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Domains
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().ForestMode
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().RootDomain
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Schema
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().SchemaRoleOwner
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().NamingRoleOwner

[Active Directory Domain]:


GetCurrentDomain() can be switch with GetComputerDomain()
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().InfrastructureRoleOwner
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().RidRoleOwner
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainMode
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Parent
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainMode
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Children
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Forest
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name

[Computer Specific]:
[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
[System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name

23 May 2014

User must change password at next logon - active directory attribute

pwdLastSet attribute is set to zero to force the user to change their password at next logon.

set the pwdLastSet attribute to -1 to remove this requirement.

05 February 2014

Find user in active directory with missing or empty attribute

Get-ADUser -Filter {-not (employeeid -like "*") }

will return all object that have the property empty.

using $null to match the filter citeria will result in an error:

Get-ADUser : The search filter cannot be recognized

30 October 2013

Register Schema Console

if you need to use schema console you need to first register the console:

run in a elevated command prompt:

regsvr32 C:\Windows\System32\schmmgmt.dll

after that you can lunch the mmc then from the File menu click Add / Remove Snap-in, select in the right window Active Directory Schema and click Add and then OK.

05 June 2013

Protect OU from accidental delettion

verifiy if all organizational units from your actuve directory domain are protected from accidental deletion:

Get-ADOrganizationalUnit -Filter * -Properties * | Select-Object name , ProtectedFromAccidentalDeletion

to protect all your organizational unit objects use:

Get-ADOrganizationalUnit -filter * | Set-ADObject -ProtectedFromAccidentalDeletion:$true

users can also be protected using:

Get-ADObject -filter {(ObjectClass -eq "user")} | Set-ADObject -ProtectedFromAccidentalDeletion:$true

17 May 2013

User's picture in active directory



To import the picture:

Import-RecipientDataProperty -Identity marius.dumitru -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\tmp\user.jpg" -Encoding Byte -ReadCount 0))


To remove the picture:

Set-Mailbox samAccountName -RemovePicture

10 May 2013

Search for inactive active directory accounts

i found a neat cmdlet that can retrieve inactive, disabled, expired or expiring active directory accounts;

full details about the command can be found on technet;

pay attention to the "-TimeSpan" argument - if you do not use the correct /accepted formatting the search will return wrong objects;



Search-ADAccount -AccountInactive -UsersOnly -SearchBase 'OU=Users,DC=domain,DC=intra' -TimeSpan 90.00:00:00.0 | Select-Object name, lastlogondate

16 April 2013

Remove spaces from distribution group alias


$groups = Get-ADGroup -Filter * -Properties mailNickname
foreach ($grup in $groups){
       Set-ADGroup -Identity $grup -Replace @{mailnickname=($grup.mailnickname.Replace(' ',''))} -Credential $cred -PassThru
       }