Category Archives: Active Directory

Powershell script to audit users who authenticated against DC servers

The story:

I have got a request from a client asking to find out which server(s) is using which domain admin or a highly privileged account as a service.

To find this I already wrote a powershell script that does this, Search the non standard/(Domain only users) and show the services and name of the servers where those accounts are configured on utilizing Remote powershell to do so and the use of a Domain Admin user.

You can refer to this link to see this article by clicking here

Creating the script process:

The same client wanted to also know which of those accounts did authenticate and wanted to know from which server/Computer did the request originate from and to which DC did it go.

I have started thinking of the process of doing so by again utilizing remote PowerShell to check against certain security events on AD to check which user among the Domain admin members did authenticate.

After sometime and with the help of some forums I managed to get script ready which looks in all Domain Controllers for users that are members of the Domain Admin groups who triggered an event ID 4624 and from which Computer did this request came from.

The Script :

# Get domain admin user list
$DomainAdminList = Get-ADGroupMember -Identity 'Domain Admins'
# Get all Domain Controller names
$DomainControllers = Get-ADDomainController -Filter * | Sort-Object HostName
# EventID
$EventID = '4624'
# Get only last 24hrs
$Date = (Get-Date).AddDays(-3)
# Limit log event search for testing as this will take a LONG time on most domains
# For normal running, this will have to be set to zero
$MaxEvent = 100

# Loop through Dcs
$DALogEvents = $DomainControllers | ForEach-Object {
    $CurDC = $_.HostName
    Write-Host "`nSearching $CurDC logs..."
    Get-WinEvent  -ComputerName $CurDC -FilterHashtable @{Logname='Security';ID=$EventID;StartTime = $Date} -MaxEvents $MaxEvent |`
    Where-Object { $_.Properties[5].Value -in $DomainAdminList.SamAccountName } |`
    ForEach-Object {
        [pscustomobject]@{SourceIP = $_.Properties[18].Value; SamAccountName = $_.Properties[5].Value;Time = $_.TimeCreated;LogonEventLocation = $CurDC}

How to run:

The Script must be run on DC with a privileged account in order to get the write results, The default time interval is set to 3 days but you can choose to increase that.

You can also change the default group where you want to search for members by changing Domain Admin groups to something else.

Screenshot of the result


The Story (Finding Domain Joined Servers Services users)

If you’re wondering which of your servers are using domain joined account or a non regular account like network service or system. You will need to go through every server’s service console and check that one by one but thanks to PowerShell this job was made like a piece of cake.


The requirement to run this script is a domain admin account since the PowerShell will require access to other servers using Remote PowerShell using Invoke command and run a Get-WMIObject script to find out those details. So in short I will write the required things for this to work

1- Logged in to Active Directory (In order for AD PowerShell module to run and find computers).

2- Domain admin account (To run the remote PowerShell on other servers and get service details)

3- Firewall for domain joined computers is open (To allow remote PowerShell to work) or have remote PowerShell enabled via GPO.

The Script will also show you the offline (inaccessible servers) and will state those servers as down as you can see in the screenshot below.

The script will also prompt you for a path to save the output. You can enter something like C:\Services.csv  as soon as you type the file path and extension it’ll be opened using Notepad.


#Check servers down and get services from the responsive servers

$Computers = Get-ADComputer -Filter { OperatingSystem -Like ‘*Windows Server*’}

$Input = ForEach ($computer in $computers){

$comp = $Computer.DNSHostName

$dist = $Computer.DistinguishedName

if (Test-Connection -Computername $comp -count 2 -Quiet )


Invoke-Command -ComputerName $comp -ScriptBlock {Get-WmiObject win32_service | where {$_.StartName -notlike “*LocalSystem*” -and $_.StartName -notlike “*LocalService*” -and $_.StartName -notlike “*NetworkService*” -and $_.StartName -notlike “*System*”} | select DisplayName,StartName,State }}

else{ Write-host $comp is down -foregroundColor red -BackGroundColor black



$Output = Read-Host “Enter File path and Name to save output to”

Out-File -FilePath $Output -InputObject $Input -Encoding ascii

Notepad $Output



Migrating DFS from 2000 Mode to 2008 step by step

The Story

Few months ago I have got a request from one of my clients regarding migrating DFS from 2012R2 to 2016.

2012R2 was migrated from 2008r2 and was based on 2000 Mode. To do this you’ve got a list of requirements as it can be migrated but certain features won’t be supported if you continue to use the 2000 Mode in DFS on Windows 2016 server.

How to Start

In this tutorial I will explain how to do this migration by doing a demo step by step and guide you through this Migration with screenshots and the required commands.

I have added a tiny comparison also to make it clear why are we going to use this particular method of migrating DFS mode and Server.


To migrate a domain-based namespace to Windows Server 2008 mode

  1. Open a Command Prompt window and type the following command to export the namespace to a file, where \\ domain \ namespace is the name of the appropriate domain and namespace and path\filename is the path and file name of the export file:
On the source DC/DFS Server

Dfsutil root export \\domain\namespace C:\filename.xml



  1. Write down the path (\\ server \ share ) for each namespace server. You must manually add namespace servers to the recreated namespace because Dfsutil cannot import namespace servers.



  1. In DFS Management, right-click the namespace and then click Delete , or type the following command at a command prompt, where \\ domain \ namespace is the name of the appropriate domain and namespace:
    Dfsutil root remove \\domain\namespace


Let’s go refresh the console and see if it’s deleted there



Next remove



I will remove the rest of the name spaces


All have been removed, Now lets remove the name spaces from the display and observe what happens to the replication groups



Replication groups didn’t get affected


  1. In DFS Management, recreate the namespace with the same name, but use the Windows Server 2008 mode, or type the following command at a command prompt, where \\ server \ namespace is the name of the appropriate server and share for the namespace root:
    Dfsutil root adddom \\server\namespace v2
I will use the UI instead of the command


Although we raised the forest and domain function forest but still the 2008 is still greyed out. Lets try to restart the DFS services on the FSMO server



After restarting



Next, I will copy all the xml files to the new server and import them there

My new server is 2016


  1. To import the namespace from the export file, type the following command at a command prompt, where \\ domain \ namespace is the name of the appropriate domain and namespace and path\filename is the path and file name of the file to import:
    Dfsutil root import merge path\filename.xml \\domain\namespace


After the Import



I will continue to import the rest of the namespaces

First we need to create them with their matching namespaces from the GUI



Now I will import and merge the xml file



After adding the NEW folder which has replicating group existing already from the previous mode. First it didn’t show up


but after navigating to the NewFolder and clicking on Replication tab then Navigate to the replication group showed the replication group underneath the Replication


What has changed?

The only noticeable thing which has changed is the NameSpace Servers everything else like ( Folder targets still the same, replication is identical to previous settings)

See this screenshot


Let’s check the access to the new namespace


Finally, Let’s import the latest namespace and its configuration (PublicFolder)



Let’s check the result on GUI


Notice the replication group for the PF didn’t come, so let’s do as we have explained before to show the replication group

Here we go


Right after this process finishes, the command creates some kind of a report with time, importing status and other related settings such as site cost, timeout.. Etc



To minimize the time that is required to import a large namespace, run the Dfsutil root import command locally on a namespace server.

Add any remaining namespace servers to the recreated namespace by right-clicking the namespace in DFS Management and then clicking Add Namespace Server , or by typing the following command at a command prompt, where \\ server \ share is the name of the appropriate server and share for the namespace root:
Dfsutil target add \\server\share


You can add namespace servers before importing the namespace, but doing so causes the namespace servers to incrementally download the metadata for the namespace instead of immediately downloading the entire namespace after being added as a namespace server.


Pfsense and Active Directory Integration

In this tutorial. I will integrate my Active directory with Pfsense in order to authenticate Users from Active directory instead of using Pfsense’s User manager.

The process will give you more options and will make managing users much easier. so in order to do that follow the following steps.

First open your Pfsense Web UI and click on System – > user manager

Next go to Servers Tab

Click + in the right corner

After you click on the + icon you will get the following page.

Fill these details accordingly, for help on how to fill these in check the below snapshot

Note: Make sure that your password is simple and contains only letters, no numbers or special characters e.g. Pfsense

When done click on Select and the result will be that you will be able to view the following OU/CN.

Now create a group on AD e.g. “PF” and create the same identical group name on Pfsense. On AD add any user to this group.

Then go back to pfsense – > system – > user manager -> goto Settings Tab – > from Authentication server select your AD and save

Now click on Diagnostic -> Authentication -> select your AD server

Type in your username and password for the user which you have added to the group pf in the AD and click test then you will see the result on top. “User: Pfsense authenticated successfully. this user is a member of these groups: pf

Hope this will help you find your way through Pfsense. 🙂

Upgrade Microsoft Domain Controller 2008 R2 to DC 2012 R2 with Exchange 2010 in the current environment.

Upgrade Microsoft Domain Controller 2008 R2 to DC 2012 R2 with Exchange 2010 in the current environment.


1- Windows 2012 R2 fully patches

2- New Windows 2012 R2 server should be joined to the Domain controller 2008r2

After you get all the prerequisites ready, start the Server manager and click on Add roles then add the ADDS role and follow the following instructions

Install the role and the n configure it as following


Add it to the existing DC


To migrate the AD Operations Master roles. The simplest way to move these roles is via PowerShell.

On Server 2012 AD PowerShell modules, this can be done from anywhere. Simply run the following command to view you current configuration, and change them:

PS C:\> netdom query FSMO


Move-ADDirectoryServerOperationMasterRole -identity “dc1” -OperationMasterRole 0,1,2,3,4


Making sure that all the roles have been migrated :

netdom query FSMO


Adding second DC



Source: Default-First-Site-Name\DC2

******* 1 CONSECUTIVE FAILURES since 2015-03-23 19:37:45

Last error: 8524 (0x214c):

The DSA operation is unable to proceed because of a DNS lookup failu


Naming Context: CN=Configuration,DC=domain,DC=local

Source: Default-First-Site-Name\DC2

******* WARNING: KCC could not add this REPLICA LINK due to error.

Naming Context: CN=Schema,CN=Configuration,DC=domain,DC=local

Source: Default-First-Site-Name\DC2

******* WARNING: KCC could not add this REPLICA LINK due to error.

Naming Context: DC=domain,DC=local

Source: Default-First-Site-Name\DC2

******* WARNING: KCC could not add this REPLICA LINK due to error.



After joining new DC you will see this error until the replication with the PDC and schema master is finished.

Use the repadmin /syncall to hasten the sync process.


After we changed the PDC and Schema master role server to the new DC and shut down the old DC for test. On Exchange 2010 server you might get the following error

Exchange Console


Current deployment

  1. Exchange 2010
  2. New DC 2012 R2 with another Additional DC installed newly.
  3. Two DC 2008R2 but have been shut down for testing.


After you shutdown or demote the old PDC or Schema master Demote Domain Controller role, Microsoft Exchange Management Console fails to retrieve any Exchange information with error message “An error caused a change in the current set of Active Directory Server settings. Restart Exchange Management console.”


Microsoft Exchange management console caches the data in the user’s profile for quick access, So whenever you try to open EMC from an existing Exchange admin profile you will get the same error.


Navigate to the following folder and delete the Exchange Management Console file.

%userprofile%\appdata\roaming\Microsoft\MMC\Exchange Management Console


Hope this was useful

Restoring an Active Directory Object after mistakenly deleting it

Active Directory Recycle Bin

Starting with Windows 2008 R2, Microsoft introduced the Active Directory recycling bin. This is great for recovering objects back into AD if they are accidentally deleted. In order to use the recycle bin feature, your forest must be running with a functional level of Windows 2008 R2. If your forest is running at this level you simply run a PowerShell command to enable it.


To enable Active Directory Recycle Bin using the Enable-ADOptionalFeature cmdlet

Click Start, click Administrative Tools, right-click Active Directory Module for Windows PowerShell, and then click Run as administrator.

Below is a sample for enabling it for

Enable-ADOptionalFeature –Identity “CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=moh10ly,DC=com” –Scope ForestOrConfigurationSet –Target



Once you have the Recycling Bin for Active Directory you will have to use LDP.exe to restore. By default the container with the deleted objects is not displayed. The following steps will allow you to see the container with the deleted objects.

Display Deleted Objects

Follow these steps to display the Deleted Objects container:

  1. To open Ldp.exe, click Start, click Run, and then type exe.
  2. On the Optionsmenu, click Controls.

3. In the Controlsdialog box, expand the Load Predefined pull-down menu, click Return deleted objects, and then click OK.


4. To verify that the Deleted Objects container is displayed:

  • To connect and bind to the server that hosts the forest root domain of your AD DS environment, under Connections, click Connect, and then Bind. (U must use SSL and port 636)
  • Click View, click Tree, and in BaseDN, type DC=<mydomain>,DC=<com>, where <mydomain>and <com> represent the appropriate forest root domain name of your AD DS environment.
  • In the console tree, double-click the root distinguished name (also known as DN) and locate the CN=Deleted Objects, DC=<mydomain>,DC=<com>container, where <mydomain>and <com> represent the appropriate forest root domain name of your AD DS environment.

Restore Deleted Objects

Once you have enabled the container to be displayed, you can now restore deleted objects from Active Directory. Below are the steps to recover a single item from the recycle bin using LDP.exe.

Follow these steps to restore a deleted Active Directory object using Ldp.exe:

  1. Open Ldp.exe from an elevated command prompt. Open a command prompt (Cmd.exe) as an administrator. To open a command prompt as an administrator, click Start. In Start Search, type Command Prompt. At the top of the Startmenu, right-click Command Prompt, and then click Run as administrator. If the User Account Control dialog box appears, enter the appropriate credentials (if requested), confirm that the action it displays is what you want, and then click Continue.
  2. To connect and bind to the server that hosts the forest root domain of your AD DS environment, under Connections, click Connect, and then click Bind.

3. On the Options menu, click Controls.

4. In the Controls dialog box, expand the Load Predefined drop-down list, click Return Deleted Objects, and then click OK.

5. In the console tree, navigate to the CN=Deleted Objects


6. Locate and right-click the deleted Active Directory object that you want to restore, and then click Modify.

7. In the Modifydialog box.

8. In Edit Entry Attribute, type isDeleted.

9.Leave the Valuesbox empty.

10. Under Operation, click Delete, and then click Enter.


11. In Edit Entry Attribute, type distinguishedName.

12. In Values, type the original distinguished name (also known as DN) of this Active Directory object.

13. Under Operation, click Replace.


14. Make sure that the Extended check box is selected, click Enter, and then click Run.


A key point to understand and remember with AD Recycle Bin is that you must restore hierarchically; a parent object must be restored before a child object. If you were to delete an entire OU and all its contents, you must first restore the OU before you can restore its contents.



Clicking on Run gives an error

“Error 0x2077 Illegal modify operation. Some aspect of the modification is not permitted.”



Disconnect and reconnect with SSL on port 636


Enter the full Distinguished path in the Values


Click on Run again and that should work







After restoring the object, I will try to login to the user’s mailbox

I’ll need to reset the user’s password after its restored.

Time to login

Resetting Usernames and Passwords from text file

I had a project to migrate users from Linux Postfix mail system to Exchange 2013 but had to do it in stages in order to use it as recommended by Microsoft, The customer had Red Hat Linux Servers with Postfix integrated with Active directory for authentication.

In order to migrate the users I installed Exchange 2007 in order to use the Microsoft tool called (Microsoft Transporter Suite) and had to reset all users (850 User) passwords to use notepad file and import it in the tool in order to migrate all users in less than a week.

I searched for any powershells that would reset users passwords on Active directory but could not find anyone that would suit my scenario and customer’s security policies until I came through a tool called “Quest One activeRoles which integrates lots of useful commands into its own powershell that have to be installed on Active Directory server to reset all users passwords.

You can find the tool either from the following link:

In order to do so I have prepared a notepad file with 2 columns “Username, password” and then copied all users and their passwords below the two columns, saved the file in .csv extension then used the following script

$data = Import-csv “C:\users_pass.csv”

foreach($line in $data) {set-QADUser $line.username -UserPassword $line.password }

Click on the snapshot to enlarge it

As shown in the snapshopt above you will have to install the application first on your DC and then run the application shell “ActiveRoles Management shell for AD” as administrator then run the commands below

$data = Import-csv “C:\users_pass.csv”

foreach($line in $data) {set-QADUser $line.username -UserPassword $line.password }


Usernames in the CSV File must be according to the format in the Snapshot above or else the command won’t be recognized.

Replication after tombstone life expired

As I was preparing for Exchange migration from 2010 to 2013 I had two DCs, one of those two DCs was off for about 8 months and has already passed the default tomb stone life so it was not authorized for replication in the forest.

Whenever I try to replicate the server I get the following error


“The following error occurred during the attempt to syncronize naming context CN=Configuration,DC=Domain,DC=Local from Domain Controller AD to Domain Controller AD2; The directory service cannot replicate with this server because the time since the last replication with this server has exceeded the tombstone lifetime. This operation will not continue.”

My FSMO roles holder and PDC is the demotesas.local domain so on this DC I will run the following command

W32tm /config /,0x1 /syncfromflags:manual /reliable:yes /update


And this

w32time & net start w32time & W32tm /resync /rediscover


On the additional DC

w32tm /config /syncfromflags:domhier /update

w32time & net start w32time & W32tm /resync /rediscover

If the above doesn’t work then I will go ahead and force replication to the tomb stoned DC by using the following command.

repadmin /regkey * +allowDivergent


Now we’ll replicate and see what happens


Problem solved



Prepare Active Directory with powershell

If you’re planning to Install Active directory on multiple DCs for backup, you can speed up this process by using the following script which is provided by Microsoft. but you’ll have to copy and paste it in notepad and save it in .ps1 extension after editing the Domain Name and Domain Netbios name.

You may also wanna change the forest mode to match the one in your environment if you already have an old DC.

# Windows PowerShell script for AD DS Deployment


Import-Module ADDSDeployment

Install-ADDSForest `

-CreateDnsDelegation:$false `

-DatabasePath “C:\Windows\NTDS” `

-DomainMode “Win2012” `

-DomainName “” `

-DomainNetbiosName “Moh10ly” `

-ForestMode “Win2012” `

-InstallDns:$true `

-LogPath “C:\Windows\NTDS” `

-NoRebootOnCompletion:$false `

-SysvolPath “C:\Windows\SYSVOL” `


Note: If you want to have a different Computer name, you will need to change that manually before you start the process below and restart after changing the computer name.

You will need to install the AD Domain Service management tools before you are able to run the powershell

Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools


When the management tools are installed you can drag and drop the powershell file to powershell window and press Enter and as soon as you do that it will ask you for the SafeModeADministratorPassword.


After you press Enter it will start the installation process


When finished it will let you know that server is going to be restarted automatically.


After restarting the server, this is how the Full computer name became.


Configure Outlook Autdiscover in GPO

To configure Outlook autodiscover in Active directory we’ll have to do the following

First open Group Policy Management from Administrator tools, After you have opened GPO you will want to create a new GPO for this purpose then follow the steps down to continue with the configuration:

1- Create a new GPO under any OU “Organization unit” you want to apply the GPO on. Then right click on it and click on Edit…

Under User configuration -> policies -> Administrative templates: Policy right click and click “add/remove templates…”

Click Add… and browse to the Office 2010 template (I’m attaching these files below) or you can just google them.

4- Under Administrative Templates: Policy Definitions – > Classic Administrative Templates (ADM) click on MS Outlook 2010 -> Exchange and on the right pane.

Enable Automatically configure profile based on AD Primary. And Enable Configure outlook anywhere user interface options.

These steps are optional but they’ll force opening outlook in order to configure it after the Client’s PC restarts.

5- When done go to User Configuration –> Windows Settings –> Scripts -> double click on Logon on the right pane

Click on Add

Browse then

Copy the below batch file to this location and attach it ” \\\SysVol\\Policies\{34E9C6C2-FCCF-45DA-908D-65A452D049F3}\User\Scripts\Logon”

When PCs restart they’ll take the new configuration.


The Outlook.txt file is the script that will be launching the Outlook configuration panel, you will need to rename the extension file from .txt to outlook.bat before uploading it to the location in the article.