Reader small image

You're reading from  Mastering Active Directory, Third Edition - Third Edition

Product typeBook
Published inNov 2021
PublisherPackt
ISBN-139781801070393
Edition3rd Edition
Concepts
Right arrow
Author (1)
Dishan Francis
Dishan Francis
author image
Dishan Francis

Dishan Francis is an IT professional with over 15 years of experience. He was a six-time Microsoft MVP in enterprise mobility before he joined Microsoft UK as a security consultant. He has maintained the RebelAdmin technology blog over the years, with lots of useful articles that focus on on-premises Active Directory services and Azure Active Directory. He has also written for other Microsoft-managed blogs such as canitpro and ITopsTalk. When it comes to managing innovative identity infrastructure solutions to improve system stability, efficiency, and security, his level of knowledge and experience places him among the very best in the field.
Read more about Dishan Francis

Right arrow

Advanced AD Management with PowerShell

The very first Active Directory (AD) instance I set up was based on Windows Server 2003. It was a completely different approach from today's Active Directory installations. In Windows Server 2003, there were a lot of prerequisite tasks, such as installing a DNS role, setting up DNS zones, and adding the domain prefix. Even those tasks were directly related to Active Directory Domain Services (AD DS), and I had to configure them separately prior to running the DCPORMO.exe command. But today, the Active Directory role installation process is very straightforward. With basic knowledge and resources, anyone can get a domain controller up and running with a few clicks.

Microsoft has made server role installations and configurations easy over the years, not just AD DS. The main reason behind all these enhancements was to save time for engineers. Installations, configurations, and repetitive infrastructure tasks take up the majority of an...

AD management with PowerShell – preparation

A PowerShell module includes assemblies, scripts, and functionalities. In order to use the functionalities, we need to import the module. After that, we can call for the contents of the module to manage relevant server roles, services, or features.

Before we start Active Directory management with PowerShell, first we need to import the ActiveDirectory module.

There are a few ways to do this. These include installing the AD DS server role or by installing Remote Server Administration Tools (RSAT):

  • AD DS server role:
    1. If we install the AD DS server role using Server Manager, the Active Directory module for Windows PowerShell is installed as a feature:

      Figure 17.1: Active Directory module for Windows PowerShell feature

    2. If the AD DS role is installed using PowerShell, we need to include the management tools by using -IncludeManagementTools. Otherwise, by default, it will not...

AD management commands and scripts

The module has 147 commands, and they can be used in countless different ways to manage the Active Directory environment. In this section, we will look at the capabilities of these commands and see how we can use them to improve Active Directory management.

I'd like to start this section by explaining how we can review the existing configuration of an Active Directory environment. The quick way to review the directory server configuration and capabilities is to use the following command:

Get-ADRootDSE

This command provides important information, such as forest and domain functional levels, the default naming context, the current time, and the currently logged-in domain controller.

The next step is to find the domain controllers in the domain. We can use the following to list the domain controller name, the IP address, the status of the global catalog server, and the Flexible Single Master Operation (FSMO) roles:

Get-ADDomainController...

Replication

Data replication is crucial for a healthy Active Directory environment. For a given domain controller, we can find its inbound replication partners using this:

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

The preceding command provides a detailed description of the replication health of the given domain controller, including the last successful replication, replication partition, server, and so on.

We can list all the inbound replication partners for the given domain using the following command:

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

In the preceding command, the scope is defined as the domain. This can be changed to the forest to get a list of the inbound partners in the forest. The output is based on the default partition. If needed, the partition can be changed using –Partition to a configuration or schema partition. It will list the relevant inbound partners for the selected...

Replicating a specific object

Once an object is added to a domain controller, it needs to be replicated to all other domain controllers. Otherwise, users will face issues during login using AD-integrated applications and services. The replication is dependent on many different factors, such as the replication schedule and intra-site connectivity. Sometimes, we need to force the replication between domain controllers:

## Replicate Object to From Domain Controller to Another ## 
$myobject = Read-Host 'What is your AD Object Includes ?' 
$sourcedc = Read-Host 'What is the Source DC ?' 
$destinationdc = Read-Host 'What is the Destination DC ?' 
$passobject = (Get-ADObject -Filter {Name -Like $myobject}) 
Sync-ADObject -object $passobject -source $sourcedc -destination $destinationdc 
Write-Host "Given Object Replicated to" $destinationdc

The preceding script will ask a few questions:

  • Name of object: This need not be a distinguished...

Users and groups

In this section, let's look at PowerShell commands and scripts that we can use to manage AD users and groups.

Last logon time

On certain occasions, we are required to find when a user successfully logs on to a domain. This can be for audit purposes or for troubleshooting purposes:

$username = Read-Host 'What is the User account you looking for ?' 
   $dcs = Get-ADDomainController -Filter {Name -like "*"} 
      foreach($dc in $dcs) 
   {  
     $hostname = $dc.HostName 
     $user = Get-ADUser $userName -Server $hostname -Properties lastLogon 
     $lngexpires = $user.lastLogon 
     if (-not ($lngexpires)) {$lngexpires = 0 } 
     If (($lngexpires -eq 0) -or ($lngexpires -gt [DateTime]::MaxValue.Ticks)) 
     { 
       $LastLogon = "User Never Logged In" 
     } 
      Else 
     { 
       $Date = [DateTime]$lngexpires 
       $LastLogon = $Date.AddYears(1600).ToLocalTime() 
     } 
  } 
  Write-Host $username "last logged on at:" $LastLogon

The preceding script will ask for the username of the account and, once it is provided, the system...

Last login date report

Periodic housekeeping in AD is required for integrity. There may be user objects that have not been used for years. If we can create a report along with the last login dates, we can use it as a reference to clean up objects:

## Script For Filter user with Last logon Time ## 
$htmlformat = "<style>BODY{background-color:LightBlue;}</style>" 
Get-ADUser -Filter * -Properties "LastLogonDate" | sort-object -property lastlogondate -descending | Select-Object Name,LastLogonDate | ConvertTo-HTML -head $htmlformat -body "<H2>AD Accounts Last Login Date</H2>"| Out-File C:\lastlogon.html 
Invoke-Expression C:\lastlogon.html

This script creates an HTML report that includes all the user accounts with their last login date timestamps:

Figure 17.4: Last login date HTML report

Some of the accounts in the above reports don't show the last login date value. It means no one has logged into those accounts...

Login failures report

It is important to know about failed attempts to log in to the DC, not just the successful attempts. These can be a result of potentially malicious activity.

The following script will create a report to indicate the login failures on a given domain controller:

## Report for DC login Failures ## 
$failedevent = $null 
$Date= Get-date  
$dc = Read-Host 'What is the Domain Controller ?' 
$Report= "C:\auditreport.html" 
$HTML=@" 
<title>Failed Login Report for $dc</title> 
<style> 
BODY{background-color :LightBlue} 
</style> 
"@ 
 $failedevent = Get-Eventlog security -Computer $dc -InstanceId 4625 -After (Get-Date).AddDays(-7) | 
 Select TimeGenerated,ReplacementStrings | 
 % { 
 New-Object PSObject -Property @{ 
 SourceComputer = $_.ReplacementStrings[13] 
 UserName = $_.ReplacementStrings[5] 
 SourceIPAddress = $_.ReplacementStrings[19] 
 Date = $_.TimeGenerated 
 } 
 } 
 $failedevent | ConvertTo-Html...

Finding the locked-out account

If password policies are defined, accounts with a large number of login failures will be locked out. Locked-out accounts in an AD environment can be found using the following command:

Search-ADAccount -Lockedout | Select name,samAccountName,Lockedout

If any of those in the list need to be unlocked, we can use the Unlock-ADAccount cmdlet to unlock an account.

For an individual account, perform the following command:

Unlock-ADAccount tuser4

For all the accounts on the list, perform the following command:

Search-ADAccount -Lockedout | Unlock-ADAccount

It is not a good practice to unlock all the accounts unless there is a specific reason.

Password expire report

Issues due to expired passwords are a common support call type for helpdesks. The following script can generate a report about expiring passwords:

## Password Expire Report ## 
$passwordreport = $null 
$dc = (Get-ADDomain | Select DNSRoot).DNSRoot 
$Report= "C:\passwordreport.html" 
$HTML=@" 
<title>Password Expire Report For $dc</title> 
<style> 
BODY{background-color :LightBlue} 
</style> 
"@ 
$passwordreport = Get-ADUser -filter * –Properties "SamAccountName","pwdLastSet","msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "SamAccountName",@{Name="Last Password Change";Expression={[datetime]::FromFileTime($_."pwdLastSet")}},@{Name="Next Password Change";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} 
$passwordreport | ConvertTo-Html -Property "SamAccountName","Last...

Review the membership of the high-level administrative groups

As a security best practice, it is important to limit the number of privileged accounts used in an Active Directory environment. Sometimes we add users to privileged groups temporarily to do certain tasks and then forget to remove the permissions later on. Therefore, it is important to review members of the sensitive groups periodically and update those as required. In Active Directory, the following security groups are identified as sensitive groups:

  • Enterprise Admins
  • Schema Admins
  • Domain Admins
  • Account Operators (if present)
  • Server Operators (if present)
  • Print Operators (if present)
  • DHCP Administrators
  • DNSAdmins

To review the membership of a sensitive group we can use the following command:

Get-ADGroupMember -Identity "Domain Admins"

In the preceding command, Domain Admins is the group name and it can be replaced with any other sensitive...

Dormant accounts

In Active Directory, at least 10% of user accounts are dormant (inactive) accounts. These accounts can represent:

  • Test accounts
  • Contractors
  • Former employees
  • Disabled accounts

It is important to review these dormant accounts periodically and remove all unnecessary accounts from Active Directory as they are a possible security threat. If it is not possible to remove some of these accounts, at least remove them from sensitive groups and disable the accounts.

We can find these accounts in Active Directory by looking at the LastLogonDate attribute value and the account status. By considering these requirements, I created the following script to find dormant accounts:

## Dormant Accounts ##
$InactiveDate = (Get-Date).Adddays(-30)
$HTML=@"
<title>Dormant Accounts Report</title>
<style>
BODY{background-color :LightBlue}
</style>
"@
$disabledaccounts = Get-ADUser -Filter {Enabled -eq $false} ...

Users with the Password Never Expires setting

In an Active Directory environment, we use password policies to enforce users to follow complexity standards and other best practices related to passwords. Users should use complex passwords and should update their passwords at regular intervals. This is one of the basic requirements of identity protection. However, if the user account has the Password Never Expires setting enabled, the user will not be forced to update the passwords according to the password policy.

We can find Active Directory user accounts that have the Password Never Expires setting enabled by using the following PowerShell commands:

Get-ADUser -Filter  {passwordNeverExpires -eq $true -and Enabled -eq $true } -Properties * | Select samAccountName,GivenName,Surname

In the preceding command, I am looking for the passwordNeverExpires attribute value and if it's set to true, it means the setting is enabled. At the same time, I also checked if the user...

Azure Active Directory PowerShell

Similar to on-prem Active Directory, we also can use PowerShell to manage Azure Active Directory.

Let's see why we should use PowerShell to manage Azure Active Directory:

  • Early bird access to features: Microsoft keeps releasing new features, bug fixes, updates, and feature enhancements more frequently to Azure AD services than on-prem Active Directory.

    Microsoft releases new features to the public in two stages. In the first stage, they are released as a preview version. This is not recommended for use in production, but IT professionals can use them for testing and provide feedback to Microsoft. At this stage, the features can have many updates and, most of the time, it will take some time to update the GUI accordingly. Some of these changes will not be available on the GUI until general release. But if we are using PowerShell, we do not have to wait. We can have early access to features as soon as they are released.

  • ...

Installation

The Azure Active Directory PowerShell for Graph module comes in two versions. The public preview version is the most recent, but it is not recommended for use in production.

The installation steps for this version can be found at https://bit.ly/3HR3EpU.

The general availability version is the stable, recommended version for production environments. It can be installed on any computer that runs Windows Server 2008 R2 or above with the latest updates. Microsoft .NET Framework 4.5 or above is also required.

Once the prerequisites are in place, perform the following steps:

  1. Log in to the computer you have selected for the Azure Active Directory PowerShell for Graph module.
  2. Launch the PowerShell console as an administrator.
  3. Run the Install-Module -Name AzureAD command. Answer Yes if it is a required repository update:

    Figure 17.10: Install AzureAD PowerShell module

  4. After installation, we can verify the module installation...

General commands

We can start by listing all the available commands under the Azure AD module, which can be done by using the following:

Get-Command -module AzureAD

We can view the full syntax for a command by using the Get-Help command. As an example, we can view the full syntax for the Get-AzureADUser command using the following:

Get-Help Get-AzureADUser

We can verify the status of Azure AD domains using the following command:

Get-AzureADDomain | fl

The preceding command helps to identify the domain verification status by referring to the value of the IsVerified attribute.

If you are using a custom domain in Azure AD, we need to verify ownership of the domain using DNS records. If it is not verified, we can retrieve the required DNS records by using the following command:

Get-AzureADDomainVerificationDnsRecord -Name M365x562652.onmicrosoft.com | fl

In the preceding example, M365x562652.onmicrosoft.com represents the domain name:

Figure...

Managing users

We can view the user account details for a known account using the following:

Get-AzureADUser -ObjectId AdeleV@M365x562652.OnMicrosoft.com | fl

In the preceding command, AdeleV@M365x562652.OnMicrosoft.com represents the UPN of the user.

We also can use user attributes to find user account details:

Get-AzureADUser -Filter "startswith(GivenName,'Adele')"

The preceding command will filter Azure AD users with GivenName as Adele.

We can also filter users based on a specific attribute value:

Get-AzureADUser -Filter "GivenName eq 'Adele'"

The preceding command will search for the exact user with the given name value Adele.

In my demo environment, I'd like to see a list of disabled accounts. I can do this using the following command:

Get-AzureADUser -All $true -Filter 'accountEnabled eq false'

We can modify the output of the filtered data further:

Get-AzureADUser -All...

Managing groups

Azure AD groups also work similarly to on-prem AD groups. They can be used to manage permissions in an effective manner. In a hybrid environment, there will be cloud-only groups as well as synced groups from the on-prem AD environment. In this section, we are going to look into group management using the Azure Active Directory PowerShell for Graph module.

Let's start with listing groups. We can search for a group using the following command:

Get-AzureADGroup -SearchString "sg"

In the preceding command, SearchString is used to define the search criteria. The preceding example will list any groups containing sg in the DisplayName field:

Figure 17.14: Search for groups

In the search result, we can see the ObjectId for the group. Once we know the ObjectId, we can see the details of the group using the following command:

Get-AzureADGroup -ObjectId 93291438-be19-472e-a1d6-9b178b7ac619 | fl

In a hybrid environment, there will...

Microsoft Graph

Microsoft Graph is like a gateway that allows users to access enormous amounts of data and collect information from:

  1. Microsoft 365 core services (for example, Office 365, Microsoft Search, OneDrive, SharePoint)
  2. Identity and Security Services (for example, Azure AD, Defender 365, Endpoint Manager)
  3. Windows 10 services

Microsoft Graph connects to the above services by using REST APIs and client libraries to retrieve required data.

We can use three methods to interact with Microsoft Graph data:

  1. The Microsoft Graph API endpoint (https://bit.ly/3DSbZHF) can be used to access data and information collected from various Microsoft services. This data can be processed and present in the way an organization/individual requires. Also, this data can be used to develop rich applications/services.
  2. Microsoft Graph connectors help to bring third-party application/service data to Microsoft Search so all company data can be searched...

Microsoft Graph Explorer

Graph Explorer is a Microsoft-developed tool that allows you to make Microsoft Graph REST API requests. This tool can be accessed using https://bit.ly/3l6EF8m.

The first thing we need to do on the page is to log in. Then we need to grant permissions to Microsoft Graph to access data. To do that, go to the Modify permissions (Preview) tab and give consent to grant relevant permissions.

Figure 17.16: Grant permissions to user

After relevant permissions are in place, we can go ahead and query data using Microsoft Graph Explorer. Let's go ahead and start with a user query.

In this example, I would like to view the account details of the IsaiahL@MSDx927799.OnMicrosoft.com user. To do that, I am going to use the GET HTTP method and the https://graph.microsoft.com/v1.0/users/IsaiahL@rebeladmin.OnMicrosoft.com query.

Figure 17.17: User query

Then Microsoft Graph responds to the query with the following data:

Figure...

Summary

PowerShell has become the most powerful script language for Windows systems. PowerShell is very useful for systems management but is also an incredibly powerful tool for managing Active Directory infrastructures. Throughout the book, I have used PowerShell for Active Directory configuration and management.

Furthermore, I have shared different commands and scripts that can be used to manage an Active Directory environment efficiently.

Toward the end of the chapter, you learned how to manage Azure AD using the Azure Active Directory PowerShell for Graph module. We also looked into Microsoft Graph and learned how to use it to manage Azure AD. In the next chapter, we will look at Azure AD closely and learn how to manage identities in a hybrid environment.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Active Directory, Third Edition - Third Edition
Published in: Nov 2021Publisher: PacktISBN-13: 9781801070393
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Dishan Francis

Dishan Francis is an IT professional with over 15 years of experience. He was a six-time Microsoft MVP in enterprise mobility before he joined Microsoft UK as a security consultant. He has maintained the RebelAdmin technology blog over the years, with lots of useful articles that focus on on-premises Active Directory services and Azure Active Directory. He has also written for other Microsoft-managed blogs such as canitpro and ITopsTalk. When it comes to managing innovative identity infrastructure solutions to improve system stability, efficiency, and security, his level of knowledge and experience places him among the very best in the field.
Read more about Dishan Francis