Tag Archives: PowerShell

Active Directory Replication Status Review Using PowerShell

Data Replication is crucial for healthy Active Directory Environment. There are different ways to check status of replication. In this article I am going to explain how you can check status of domain replication using PowerShell.

For a given domain controller we can find its inbound replication partners using, 

Get-ADReplicationPartnerMetadata -Target REBEL-SRV01.rebeladmin.com

Above command provide detail description for the given domain controller including last successful replication, replication partition, server etc. 

We can list down all the inbound replication partners for given domain using, 

Get-ADReplicationPartnerMetadata -Target "rebeladmin.com" -Scope Domain

In above command the scope is defined as the domain. this can change to forest and get list of inbound partners in the forest. The output is for default partition.  If needed the partition can change using – Partition to Configuration or Schema partition. It will list down the relevant inbound partners for given partition. 

Associated replication failures for a site, forest, domain, domain controller can find using Get-ADReplicationFailure cmdlet. 

Get-ADReplicationFailure -Target REBEL-SRV01.rebeladmin.com

Above command will list down the replication failures for the given domain controller. 

Replication failures for domain can find out using, 

Get-ADReplicationFailure -Target rebeladmin.com -Scope Domain

Replication failures for forest can find out using, 

Get-ADReplicationFailure -Target rebeladmin.com -Scope Forest

Replication failures for site can find out using, 

Get-ADReplicationFailure -Target LondonSite -Scope Site

In command, LondonSite can replace using relevant site name. 

Using both Get-ADReplicationPartnerMetadata and Get-ADReplicationFailure, following PowerShell script can provide report against specified domain controller. 

## Active Directory Domain Controller Replication Status##

$domaincontroller = Read-Host 'What is your Domain Controller?'

## Define Objects ##

$report = New-Object PSObject -Property @{

ReplicationPartners = $null

LastReplication = $null

FailureCount = $null

FailureType = $null

FirstFailure = $null


## Replication Partners ##

$report.ReplicationPartners = (Get-ADReplicationPartnerMetadata -Target $domaincontroller).Partner

$report.LastReplication = (Get-ADReplicationPartnerMetadata -Target $domaincontroller).LastReplicationSuccess

## Replication Failures ##

$report.FailureCount  = (Get-ADReplicationFailure -Target $domaincontroller).FailureCount

$report.FailureType = (Get-ADReplicationFailure -Target $domaincontroller).FailureType

$report.FirstFailure = (Get-ADReplicationFailure -Target $domaincontroller).FirstFailureTime

## Format Output ##

$report | select ReplicationPartners,LastReplication,FirstFailure,FailureCount,FailureType | Out-GridView

In this command, it will give option for engineer to specify the Domain Controller name. 

$domaincontroller = Read-Host 'What is your Domain Controller?'

Then its creates some object and map those to result of the PowerShell command outputs. Last but not least it provides a report to display a report including, 

Replication Partner (ReplicationPartners)

Last Successful Replication (LastReplication)

AD Replication Failure Count (FailureCount)

AD Replication Failure Type (FailureType)

AD Replication Failure First Recorded Time (FirstFailure)


Further to Active Directory replication topologies, there are two types of replications.

1) Intra-Site – Replications between domain controllers in same Active Directory Site

2) Inter-Site – Replication between domain controllers in different Active Directory Site

We can review AD replication site objects using Get-ADReplicationSite cmdlet. 

Get-ADReplicationSite -Filter *

Above command returns all the AD replication sites in the AD forest. 


We can review AD replication site links on the AD forest using, 

Get-ADReplicationSiteLink -Filter *

In site links, most important information is to know the site cost and replication schedule. It allows ro understand the replication topology and expected delays on replications. 

Get-ADReplicationSiteLink -Filter {SitesIncluded -eq "CanadaSite"} | Format-Table Name,Cost,ReplicationFrequencyInMinutes -A

Above command list all the replication sites link included CanadaSite AD site along with the site link name, link cost, replication frequency. 

A site link bridge can use to bundle two or more site links and enables transitivity between site links.

Site link bridge information can retrieve using, 

Get-ADReplicationSiteLinkBridge -Filter *

Active Directory sites may use multiple IP address segments for its operations. It is important to associate those with the AD site configuration so domain controllers know which computer related to which site. 

Get-ADReplicationSubnet -Filter * | Format-Table Name,Site -A

Above command will list down all the Subnets in the forest in a table with subnet name and AD site.


Bridgehead servers are operating as the primary communication point to handle replication data which comes in and go out from AD site. 

We can list down all the preferred bridgehead servers in a domain using, 

$BHservers = ([adsi]"LDAP://CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,DC=rebeladmin,DC=com").bridgeheadServerListBL

$BHservers | Out-GridView

In above command the attribute value bridgeheadServerListBL retrieve via ADSI connection. 

We can list down all of these findings using on script. 

## Script to gather information about Replication Topology ##

## Define Objects ##

$replreport = New-Object PSObject -Property @{

Domain = $null


## Find Domain Information ##

$replreport.Domain = (Get-ADDomain).DNSroot

## List down the AD sites in the Domain ##

$a = (Get-ADReplicationSite -Filter *)

Write-Host "########" $replreport.Domain "Domain AD Sites" "########"

$a | Format-Table Description,Name -AutoSize

## List down Replication Site link Information ##

$b = (Get-ADReplicationSiteLink -Filter *)

Write-Host "########" $replreport.Domain "Domain AD Replication SiteLink Information" "########"

$b | Format-Table Name,Cost,ReplicationFrequencyInMinutes -AutoSize

## List down SiteLink Bridge Information ##

$c = (Get-ADReplicationSiteLinkBridge -Filter *)

Write-Host "########" $replreport.Domain "Domain AD SiteLink Bridge Information" "########"

$c | select Name,SiteLinksIncluded | Format-List

## List down Subnet Information ##

$d = (Get-ADReplicationSubnet -Filter * | select Name,Site)

Write-Host "########" $replreport.Domain "Domain Subnet Information" "########"

$d | Format-Table Name,Site -AutoSize

## List down Prefered BridgeHead Servers ##

$e = ([adsi]"LDAP://CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,DC=rebeladmin,DC=com").bridgeheadServerListBL

Write-Host "########" $replreport.Domain "Domain Prefered BridgeHead Servers" "########"


## End of the Script ##

The only thing we need to change is the ADSI connection with relevant domain DN. 

$e = ([adsi]"LDAP://CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,DC=rebeladmin,DC=com")

This marks the end of this blog post. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

How to re-enable Network Interface in Azure VM?

In Hyper-V or VMware virtualization environment, Enable/Disable NIC in a VM is not a big deal. Even if you do not have NIC or valid IP configure, administrators still can connect to VM as it does have “Console” access. Few weeks ago, I received an email from one of my regular blog readers. He accidently disabled NIC in azure vm and he lost RDP access to it. since there is no console access like other on-premises virtualization solution, of cause he was panicking. In this blog post I am going to share what you can do to re-enable your Azure VM NIC in such scenario. 

In my demo setup, I have an active azure VM running with private IP address. 


I logged in to VM as administrator and disable the NIC.

Now I need to regain the RDP access to server. in order to do that, log in to Azure Portal as Global Administrator and click on Cloud Shell button in right hand top corner. 


When window load up makes sure you are using PowerShell option. 


Now we need to find out the NIC details of the VM that we having issues with. We can do this using,

Get-AzureRmNetworkInterface -ResourceGroupName "REBELADMIN-DEMO" 

In this command, -ResourceGroupName represent the resource group that VM belongs to. In my demo setup I only have one VM under that resource group.  but if you have more VMs it can be hard to find the relevant info. In that case I recommend to use portal itself to view this info.

In here, note down the network interface name, IP address and allocation method you using. 


Now, we need to assign a new IP address to the same nic from same subnet. It can be done using,

$Nic = Get-AzureRmNetworkInterface -ResourceGroupName "REBELADMIN-DEMO" -Name "rebeladmin-vm1123"

$Nic.IpConfigurations[0].PrivateIpAddress = ""

$Nic.IpConfigurations[0].PrivateIpAllocationMethod = "Static"

$Nic.Tag = @{Name = "Name"; Value = "Value"}

Set-AzureRmNetworkInterface -NetworkInterface $Nic

In above commands, rebeladmin-vm1123 represent the network interface name. is the new ip address for the network interface. PrivateIpAllocationMethod define the ip allocation method. Set-AzureRmNetworkInterface cmdlet sets the network interface configuration. 


Great!! Now I got my RDP access back with new IP address.


But it is not the original IP it had, now we can change it back with,

$Nic2 = Get-AzureRmNetworkInterface -ResourceGroupName "REBELADMIN-DEMO" -Name "rebeladmin-vm1123"

$Nic2.IpConfigurations[0].PrivateIpAddress = ""

$Nic2.IpConfigurations[0].PrivateIpAllocationMethod = "Static"

$Nic2.Tag = @{Name = "Name"; Value = "Value"}

Set-AzureRmNetworkInterface -NetworkInterface $Nic2


Once it is applied, I can access server via RDP and now it has same private IP address it had.


If you using dynamic IP allocation method, you need to make it static, then change the ip and go back to dynamic mode. 

This marks the end of this blog post. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Step-by-Step Guide to setup Active Directory Lightweight Directory Services (AD LDS)

When we talk about active directory we refer it as one service but AD DS attached to many other components as well. DNS, Group Policies, SYSVOL replication are few example for this. Each of these components need to operate well in order to run healthy active directory environment. It doesn’t come easy, its involve with investment on resources, time and skills. In Active Directory Service, the core values are centralized identity management, authentication and authorization capabilities. All these extra components make it easy to archive its core values but same time it also opens up risks such as dependencies and security. Failure or compromise of these components/service will make impact on entire active directory infrastructure. 

Microsoft Windows Core and Nano Servers also count as “Operating Systems”. These doesn’t have fancy GUIs, sparkly applications running. But it is still doing the job of operating system. It allows users to build it from scratch according to their requirements. It also increases the server up time (less updates), reliability, performance and security. Soon after Microsoft releases the First Active Directory version, there were conversation start specially from application developers by requesting a version with pure LDAP capabilities. They wanted to element all these dependencies and management requirements, so they can focus on application development upon core AD functions. After windows server 2003, Microsoft releases Active Directory Application Mode (ADAM) which allowed administrators to run “cut down” version of active directory without group policies, Kerberos, file replication etc. It can run on desktop computer or member server similar to any other windows service. Same time it was providing all core values of Active Directory Service. With Windows server 2008, Microsoft renamed it to “Active Directory Lightweight Directory Services” and allow to install the role using Server Manager. This version provided more control and visibility to administrators to deploy and managed LDS instances. This was continued with all the AD DS versions after that and included in windows server 2016 too. 

LDS installation 

In Windows server 2016 Operating system, it can install using Server Manager. in order to install LDS, User need to log in with local administrator privileges. 

Once log in to the Server Manager, click on Add Roles and Features. Then follow the wizard and select Active Directory Lightweight Directory Services under server roles and proceed with the enabling the role. 


Once the role is installed, click on Post-Deployment Configuration wizard in Server Manager. LDS can setup two way. One is as a unique instance and other one as a replica of an existing instance. Replica option is similar to clone copy of an existing instance. This is useful especially in development environment where engineers can maintain number of application versions. 


In next window, we can define name and description for the LDS instance. 


In next window, we can define the LDS port. By default, LDAP port is set to 389 and SSL port is set to 636. if you running multiple instance these can be change accordingly. 

After that, we can create application directory partition. This allows applications to use this partition as data repository to store application related data. If application is capable of creating partition this step is not necessary and can create relevant partition during the application deployment process. When defining the application partition name, it need to provide as distinguished name format. 


Next step is to define location to store LDS data files. After that it gives option to specify service account for LDS. If its workgroup environment you can use network service account or local user account for it. if its domain environment it can be AD user account.


After that we need to define AD LDS administrator account. By default, it selects the user account that used for the installation. If needs it can change to different account or group.

Once we define the administrator account, next step is to define which LDIF file to import. It is a text file which represent data and commands which will use by LDAP instance. It can contain one or more LDIF files. These files are depending on application requirements.  As example if its users’ functionalities the relevant file will be MS-User.LDF.


This will complete the AD LDS installation and once it completed we can create relevant object and manage them. There is two way to connect to it. one way is to connect using ADSI edit tool. 


LDS objects also can manage using PowerShell cmdlets. It is same commands which users for AD DS and only difference is to define the DN and Server. 

New-ADUser -name “tidris” -Displayname “Talib Idris” -server ‘localhost:389’ -path “CN=webapp01,DC=rebeladmin,DC=com”

The above command will create user account called tidris on local LDS instance runs on 389. Its DNS path is “CN=webapp01,DC=rebeladmin,DC=com”

Get-ADUser -Filter * -SearchBase "CN=webapp01,DC=rebeladmin,DC=com" -server ‘localhost:389’ 

Above command going to list all the user accounts in LDS instance CN=webapp01,DC=rebeladmin,DC=com


AD LDS also can install in desktop operating system using windows features option under Program and Features. The installation steps are similar to server version. once enabled the feature, the setup wizard can find under Administrative Tools. 


This marks the end of this blog post. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Troubleshooting Active Directory Replication Issues (PowerShell Guide)

There are certain windows cmdlets and utilities which we can use for replication issues troubleshooting purpose. Among those, Repadmin.exe is most commonly used Microsoft utility. This is available in servers which have AD DS or AD LDS role installed. It is also part of Remote Server Administration Tools (RSAT). This utility recommended to run as Domain Administrator or Enterprise Administrator. However, it is also possible to delegate permission only to review and manage replication. 

Let’s see it’s in action 

repadmin /replsummary /bydest

above command summarizes the replication status for all domain controllers based on the replication destination. This parameter does not display the source domain controller.

repadmin /replsummary /bysrc

above command summarizes the replication status for all domain controllers based on the replication source. This parameter does not display the destination domain controller.

repadmin /showrepl REBEL-SRV01.therebeladmin.com 

above command shows the replication partners for REBEL-SRV01.therebeladmin.com and the status of last sync attempt. 

repadmin /showrepl /errorsonly 

above command will list down the replication partners which have replication errors (last sync attempt failed) 

we also can view results in CSV format.

repadmin /showrepl /csv


repadmin /syncall REBEL-SRV01 dc=therebeladmin,dc=com

above command initiates domain directory partition synchronization with all replication partners of REBEL-SRV01. 

It will also indicate if there were any issues by doing it.


repadmin /queue

above command shows if there are any unprocessed inbound replications requests. If system keep que requests it can be due to high number of AD changes, System resource issue or too many replication partners. 

repadmin /showchanges REBELNET-PDC01 d3f89917-5fff-40a8-scc2-b148b60d9309 dc=therebeladmin,dc=com

above command list down the changes which are not replicated between server REBELNET-PDC01 and REBEL-SRV01. In here REBEL-SRV01 is the source server and it is listed with object GUID. 


repadmin /replicate REBEL-SRV01 REBELNET-PDC01 dc=therebeladmin,dc=com

above command initiate immediate directory partition replication from REBELNET-PDC01 to REBEL-SRV01.

Apart from the repadmin, there are certain PowerShell cmdlets which we can use to troubleshoot replication issues. Get-ADReplicationFailure cmdlet is one of those which can collect data about replication failures. 

Get-ADReplicationFailure -Target REBEL-SRV01

Above command will collect information about replication failures associated with REBEL-SRV01. 

This also can do with multiple servers. 

Get-ADReplicationFailure -Target REBEL-SRV01,REBELNET-PDC01

Further we can target all the domain controllers in the domain.

Get-ADReplicationFailure -Target "therebeladmin.com" -Scope Domain

Or even entire forest

Get-ADReplicationFailure -Target " therebeladmin.com" -Scope Forest

Get-ADReplicationConnection cmdlet can list down replication partner details for the given domain controller. 

Get-ADReplicationConnection -Filter *

Above command will list down all replication connection for the domain controller you logged in. 


We also can filter the replication connections based on the attributes. 

Get-ADReplicationConnection -Filter {ReplicateToDirectoryServer -eq "REBEL-SRV01"}

Above command will list down the replication connections with destination server as REBEL-SRV01.

We also can force sync object between domain controllers. 

Sync-ADObject -object “adam” -source REBEL-SRV01 -destination REBELNET-PDC01

Above command will sync user object adam from REBEL-SRV01 to REBELNET-PDC01

This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

How to Seize FSMO Roles? (PowerShell Guide)

In AD environment, FSMO role seize process only should use in a disaster where you cannot recover the FSMO role holder. It should be using for day to day operations. Some of the FSMO roles (RID, Domain Naming Master, Schema Master) can still afford few hours’ downtime with minimum business impacts. There for do not use the Seize option as the first option if still FSMO role holder can recover or fix. 

Once seize process is completed, the old FSMO role holder should not bring online again. It is recommended to format and remove it from network. In any given time, it is not possible to have same FSMO role appear in two servers in same domain.

In following example, there are two domain controllers in the infrastructure. REBEL-SDC02 is the FSMO role holder and REBEL-PDC-01 is additional domain controller. Due to hardware failure, I cannot bring REBEL-SDC02 online and I need to seize the FSMO roles. 


In order to seize the roles following command can use,

Move-ADDirectoryServerOperationMasterRole -Identity REBEL-PDC-01 -OperationMasterRole SchemaMaster, DomainNamingMaster, PDCEmulator, RIDMaster, InfrastructureMaster -Force


This command will take few minutes to complete as in background it will try to connect to original FSMO role holder. 

The only change in the command from FSMO role transfer is the -Force at the end. Otherwise its exact same command. You also can seize individual role by using Move-ADDirectoryServerOperationMasterRole -Identity REBEL-PDC-01 -OperationMasterRole <FSMO Role> -Force

In their <FSMO Role> can be replaced by the actual FSMO role value.

Once command completed we can test the new FSMO role holder. 


As we can see REBEL-PDC-01 become the new FSMO role holder. 

This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

How to Enable Active Directory Recycle Bin? (PowerShell Guide)

Most common active directory related disasters are due to accidently deleted objects. Once object is deleted from active directory, it is not permanently deleteing from the active directory same time. As soon as an object deleted, it will set the isDeleted object value to True and move the object under CN=Deleted Object.


Then the it is stay there till system reaches the tombstone lifetime value. By default, it is 180 days and this can be change if required. As soon as object passes the tombstone lifetime, it is available for permanent deletion. When I explain about the active directory database in previous section I mentioned about “online defragmentation”. It is uses garbage collector service to remove the deleted objects from the active directory database and release that space to database. This service runs in every 12 hours’ time. Once deleted object exceeded the tombstone lifetime value, it will be permanently removed in next garbage collector service cycle. the problem with this one is, during the tombstone process most of the object values are striped off. So even you were able to recover, these objects values will need to re-enter. 

With windows server 2008 R2, Microsoft introduced Active Directory Recycle Bin feature. When this feature is enabled, once object is deleted, it’s still set isDeleted object value to True and move the object under CN=Deleted Object. but instead of tombstone lifetime, now its control by Deleted Object Lifetime (DOL). Object attributes will remain same in this stage and it is recoverable easily. By default, the DOL value is equal to tombstone lifetime. This value can change by modifying msDS-deletedObjectLifetime object value. Once its exceeded the DOL, it is moved in to Recycled state and isRecycled object value set to True. By this state, it will not be able to recovered and it will be in that state till tombstone lifetime value exceed. After it reach the value it will be permanently delete from the AD. 

Active Directory Recycle Bin feature required minimum of windows server 2008 R2 domain and forest functional level. Once this feature is enabled it cannot be disabled. 

This feature can be enable using,

Enable-ADOptionalFeature 'Recycle Bin Feature' -Scope ForestOrConfigurationSet -Target rebeladmin.com

In above -Target can be change with your domain name. 


Once it is enabled, we can revive the objects which is deleted using,

Get-ADObject -filter 'isdeleted -eq $true' -includeDeletedObjects

It will search for the objects where isdeleted attributes set to true. 

Now we know the deleted object and it can be restore using, 

Get-ADObject -Filter 'samaccountname -eq "dfrancis"' -IncludeDeletedObjects | Restore-ADObject

The above will restore user object dfrancis


This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Find Active Directory Objects (PowerShell Guide)

Active Directory can hold near 2 billion objects. When the number of objects grows, the requirement for affective object filtering grows as well. Active Directory have several GUI options to search/filter specific objects. We also can filter objects using PowerShell. 

In previous posts, we learned about Get-ADUser and Get-ADComputer cmdlets and how it can be used with other commands to filter out objects from Active directory and perform administrative tasks.  It is also can use to retrieve specific attribute values from filtered objects. 

Get-ADUser -Identity user1 -Properties *

In above command, it will list down all the attributes and its values associated with user1. This helps to find exact attributes names and common values which can use for further filtering. 

I need to know values of Name, UserPrincipalName and Modified for all the users. Following command will create a table with attributes and its values. 

Get-ADUser -Filter * -Properties Name,UserPrincipalName,Modified | ft Name,UserPrincipalName,Modified


I can see some accounts in the list which is service accounts and administrator account. I only want to see the accounts which is in Kingston office

Get-ADUser -Filter {City -like "Kingston"} -Properties Name,UserPrincipalName,Modified | ft Name,UserPrincipalName,Modified  

With above it filters it further based on the City value.

Now I have the list of data I needed, I like to export it to a CSV file for future use. 

Get-ADUser -Filter {City -like "Kingston"} -Properties Name,UserPrincipalName,Modified | select-object Name,UserPrincipalName,Modified | Export-csv -path C:\ADUSerList.csv

So, above example shows how search query can build up from granular level to find the exact information needed from objects. 

Search-ADAccount cmdlet can also use to search for the active directory objects based on account and password status. Full syntax for the cmdlet can retrieve using,

Get-Command Search-ADAccount -Syntax 

As an example, it can use to filter the accounts which is locked out. 

Search-ADAccount -LockedOut | FT Name,UserPrincipalName

Above command will list down all the lockout accounts with name and UPN

Unlikely the graphical tools, Powershell queries can build to filter the exact objects and data from active directory. 

This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Active Directory Managed Service Accounts (PowerShell Guide)

Services Accounts are recommended to use when install application or services in infrastructure. It is dedicated account with specific privileges which use to run services, batch jobs, management tasks. In most of the infrastructures, service accounts are typical user accounts with “Password never expire” option. Since these service accounts are not been use regularly, Administrators have to keep track of these accounts and their credentials. I have seen in many occasions where engineers face in to issues due to outdated or misplace service account credential details. Pain of it is, if you reset the password of service accounts, you will need to update services, databases, application settings to get application or services up and running again. Apart from it Engineers also have to manage service principle names (SPN) which helps to identify service instance uniquely. 

After considering all these challenges Microsoft has introduced Managed Service Accounts with windows server 2008 R2. These accounts got following features and limitations,

No more password management. It uses a complex, random, 240-character password and change that automatically when it reaches the domain or computer password expire date.

It cannot be lock out or use for interactive login. 

One managed service account only can use in one computer. it cannot be share between multiple computers

Simplified SPN Management – System will automatically change the SPN value if sAMaccount details of the computer change or DNS name property change. 

In order to create Managed service account, we can use following command, I am running this from the domain controller.

New-ADServiceAccount -Name "MyAcc1" -RestrictToSingleComputer

In above command I am creating service account called MyAcc1 and I am restricting it to one computer. 

Next step is associate the service account with the Host REBEL-SRV01 where I am going to use this service account. 

Add-ADComputerServiceAccount -Identity REBEL-SRV01 -ServiceAccount "MyAcc1"

Next step is to install service account in the REBEL-SRV01 server. We need active directory PowerShell module for this. We can install it using RSAT tools. Once its ready run the command,

Install-ADServiceAccount -Identity "MyAcc1"

Once it’s done, we can test it using,

Test-ADServiceAccount "MyAcc1"

It is return the value True which means the test is successful. 

From active directory server, we can verify the service account by running
Get-ADServiceAccount "MyAcc1"
Tip – When configure the Manager service account in service make sure to leave the password as empty. You do not need to define any password there as system auto generate the password. 
This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Manage Active Directory Organizational Units (OU) with PowerShell

Similar to any other active directory object, OU structure can manage using Active Directory Administrative Center (ADAC), Active Directory Users and Computers (ADUC) MMC and PowerShell. In this post, I am going to demonstrate how to manage OU structure using PowerShell. 

New Organization Unit can create using New-ADOrganizationalUnit cmdlet. The complete syntax can review using,

Get-Command New-ADOrganizationalUnit -Syntax

As the first step, I am going to create new OU called “Asia” to represent Asia Branch. 

New-ADOrganizationalUnit -Name "Asia" -Description "Asia Branch"

In above command -Description defines description for new OU. When there is no path defined, it will create the OU under the root. We can review the details of the new OU using,

Get-ADOrganizationalUnit -Identity “OU=Asia,DC=rebeladmin,DC=com”


We can add/change values of OU attributes using, 

Get-ADOrganizationalUnit -Identity “OU=Asia,DC=rebeladmin,DC=com” | Set-ADOrganizationalUnit -ManagedBy “Asia IT Team”

Above command will set ManagedBy Attribute to “Asia IT Team”

Tip – When you use ManagedBy attribute, make sure to use existing active directory object for the value. It can be individual user object or group object. If not, command will fail. 

 “Protect from Accidental Deletion” for OU object is nice small safe guard we can apply. It will prevent Accidental OU object deletion. This will be apply by default if you create OU using ADAC or ADUC. 

Get-ADOrganizationalUnit -Identity “OU=Asia,DC=rebeladmin,DC=com” | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true

As the next step, I am going to create Sub OU under Asia OU Called “Users”.

New-ADOrganizationalUnit -Name "Users" -Path “OU=Asia,DC=rebeladmin,DC=com” -Description “Users in Asia Branch” -ProtectedFromAccidentalDeletion $true

Above command will create OU called Users under path OU=Asia,DC=rebeladmin,DC=com. It is also protected from accidental deletion. 

Now we have OU structure created and next step is move objects to it. for that we can use Move-ADObject cmdlet. 

Get-ADUser “tuser3” | Move-ADObject -TargetPath “OU=Users,OU=Asia,DC=rebeladmin,DC=com”

Above command will find user “tuser3” and move object to OU=Users,OU=Asia,DC=rebeladmin,DC=com

We also can move multiple object to the new OU. 

Get-ADUser -Filter 'Name -like "Test*"' -SearchBase “OU=Users,OU=Europe,DC=rebeladmin,DC=com” | Move-ADObject -TargetPath “OU=Users,OU=Asia,DC=rebeladmin,DC=com”

In above command, It will first search all the user accounts what is starts with “Test” in OU=Users,OU=Europe,DC=rebeladmin,DC=com and then move all objects it found to new OU path. 

Tip – If you have ProtectedFromAccidentalDeletion enable on objects, it will not allow to move object to different OU. It need to remove before object move.

If we need to remove OU object it can be done using Remove-ADOrganizationalUnit cmdlet. 

Remove-ADOrganizationalUnit “OU=Laptops,OU=Europe,DC=rebeladmin,DC=com”

Above command will remove OU=Laptops,OU=Europe,DC=rebeladmin,DC=com Organization Unit. 

This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Create Active Directory User Objects using PowerShell

There are few ways to create user objects in Active Directory. If it’s using GUI, it can be done using Active Directory Administrative Center or Active Directory Users and Computers MMC. If it is using command line, it can be done using windows command-line or PowerShell. In this demo, I am going to show how we can create user object using PowerShell. 

In order to create user object in active directory we can use New-ADUser cmdlet in PowerShell. You can view the full syntax for the command along with the accepted data types using,

Get-Command New-ADUser -Syntax

In order to create a New User account using PowerShell the minimum value you need to pass is -Name. it will create a disabled user account and you still can define values for other attributes later. 

This is a sample which can use to create a user account,

New-ADUser -Name "Talib Idris" -GivenName "Talib" -Surname "Idris" -SamAccountName "tidris" -UserPrincipalName "tidris@rebeladmin.com" -Path "OU=Users,OU=Europe,DC=rebeladmin,DC=com" -AccountPassword(Read-Host -AsSecureString "Type Password for User") -Enabled $true

In the command,

Name – Defines the Full Name

Given Name – Defines the First Name

Surname – Defines the Surname

SamAccountName – Defines the User Name

UserPrincipalName – Defines the UPN for the user account

Path – Defines the OU path. The default location is “CN=Users,DC=rebeladmin,DC=com”

AccountPassword – This will allow user to input password for the user and system will convert it to the relevant data type

Enable – defines if the user account status is enabled or disabled. 

You can create a user account with minimum attributes such as Name and UPN. Then later can define a password and enable the account. User account cannot enable without a password. To define password can use Set-ADAccountPassword -Identity cmdlet and to enable account can use Enable-ADAccount -Identity cmdlet. 
Instead of executing multiple commands to create multiple user objects, we can create a CSV (comma-separated values) file which include data for attributes and use it to create accounts in one go. 
In demo I am using following CSV file. 

Import-Csv "C:\ADUsers.csv" | ForEach-Object {
$upn = $_.SamAccountName + “@rebeladmin.com” 
New-ADUser -Name $_.Name `
 -GivenName $_."GivenName" `
 -Surname $_."Surname" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $upn `
 -Path $_."Path" `
 -AccountPassword (ConvertTo-SecureString “Pa$$w0rd” -AsPlainText -force) -Enabled $true
In above script Import-Csv cmdlet used to import the CSV file created. I have defined parameter $upn = $_.SamAccountName + “@rebeladmin.com” to use for the  -UserPrincipalName value. In script, I have defined a common password for all the accounts using -AccountPassword (ConvertTo-SecureString “Pa$$w0rd” -AsPlainText -force) 
This marks the end of this blog post. Hope this was useful. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.