Mandatory Prerequisites and Checks - Before running any Active Directory (AD) PowerShell script

Before running any Active Directory (AD) PowerShell scripts, there are a few mandatory prerequisites and checks. Skipping these is the #1 reason for scripts fail


1.Install Required Module (RSAT)

Check: You must have the AD module installed.

Script:
Get-Module -ListAvailable ActiveDirectory

Install (if missing):

Script:
Add-WindowsCapability -Online -Name "Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0"


2.Import Active Directory Module

Script:
Import-Module ActiveDirectory

3.Run PowerShell as Administrator

Right-click → Run as Administrator

Required for:

  • Creating users

  • Modifying groups

  • Resetting passwords

4.Ensure Domain Connectivity

Check if your system is connected to the domain:

whoami

Or

Script:
Test-ComputerSecureChannel

Should return True

5.Verify Permissions (VERY IMPORTANT)

Task    Required Permission
Create user        Account Operators / Domain Admin
Reset password        Helpdesk / delegated rights
Delete objects            Full control

If not, scripts will fail silently or throw access errors.

6.Set Execution Policy

By default, scripts may be blocked.

Script:
Set-ExecutionPolicy RemoteSigned -Scope Process

7.Use Correct OU / DN Format

Always verify Distinguished Name:

Script:
Get-ADOrganizationalUnit -Filter * | Select Name,DistinguishedName

Example: OU=Users, DC=company, DC=com

8.Test with -WhatIf (Safe Mode)

Before running any destructive script:

Script:
Disable-ADAccount username -WhatIf

Shows what will happen without executing

9.Use Logging (Best Practice)

Script:
Start-Transcript -Path "C:\Logs\ADScript.log"

10.Validate Input Data (CSV / Variables)

Always check your CSV:

Script:
Import-Csv "C:\users.csv"

Avoid:

  • Missing columns

  • Wrong headers

  • Extra spaces

11.Check AD Server Availability

Script:
Get-ADDomainController

Ensures domain controller(DC) is reachable

12.Time Sync (Kerberos Requirement)

If system time is wrong → authentication fails

Script:
w32tm /query /status

13.Advanced – Recommended

- Use a test OU / lab environment

- Backup before bulk operations:

  • Users
  • Groups
  • GPOs

- Use try/catch error handling in scripts

- Avoid hardcoding passwords in production

14.Admin Practice - Before running any script in production

follow this flow:
Lab Test → WhatIf → Small Batch → Full Run


Active Directory Pre-Flight Check Script

# AD Pre-Flight Check Tool
# Run before executing any AD automation scripts

Write-Host "===== Active Directory Pre-Flight Check =====" -ForegroundColor Cyan

$errors = 0

# 1. Check Admin Rights
Write-Host "`n[1] Checking Admin Privileges..."
if (-not ([Security.Principal.WindowsPrincipal] `
[Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltinRole]::Administrator)) {
    Write-Host "Not running as Administrator" -ForegroundColor Red
    $errors++
} else {
    Write-Host "Running as Administrator" -ForegroundColor Green
}

# 2. Check AD Module
Write-Host "`n[2] Checking Active Directory Module..."
if (Get-Module -ListAvailable -Name ActiveDirectory) {
    Import-Module ActiveDirectory
    Write-Host "AD Module Loaded" -ForegroundColor Green
} else {
    Write-Host "ActiveDirectory module not installed" -ForegroundColor Red
    $errors++
}

# 3. Check Domain Connectivity
Write-Host "`n[3] Checking Domain Connectivity..."
try {
    if (Test-ComputerSecureChannel) {
        Write-Host "Connected to Domain" -ForegroundColor Green
    } else {
        Write-Host "Not connected to Domain" -ForegroundColor Red
        $errors++
    }
} catch {
    Write-Host "Domain check failed" -ForegroundColor Red
    $errors++
}

# 4. Check Domain Controller
Write-Host "`n[4] Checking Domain Controller Availability..."
try {
    $dc = Get-ADDomainController -Discover -ErrorAction Stop
    Write-Host "DC Found: $($dc.HostName)" -ForegroundColor Green
} catch {
    Write-Host "No Domain Controller reachable" -ForegroundColor Red
    $errors++
}

# 5. Check Permissions (basic test)
Write-Host "`n[5] Checking AD Permissions..."
try {
    Get-ADUser -Filter * -ResultSetSize 1 | Out-Null
    Write-Host "AD Read Access OK" -ForegroundColor Green
} catch {
    Write-Host "No permission to query AD" -ForegroundColor Red
    $errors++
}

# 6. Execution Policy
Write-Host "`n[6] Checking Execution Policy..."
$policy = Get-ExecutionPolicy
Write-Host "Current Policy: $policy"
if ($policy -eq "Restricted") {
    Write-Host "Execution Policy may block scripts" -ForegroundColor Yellow
}

# 7. Time Sync Check
Write-Host "`n[7] Checking Time Synchronization..."
try {
    w32tm /query /status | Out-Null
    Write-Host "Time service running" -ForegroundColor Green
} catch {
    Write-Host "Time sync issue detected" -ForegroundColor Yellow
}

# 8. OU Validation (Optional Input)
$ou = Read-Host "`n[8] Enter OU to validate (or press Enter to skip)"
if ($ou) {
    try {
        Get-ADOrganizationalUnit -Identity $ou -ErrorAction Stop
        Write-Host "OU exists: $ou" -ForegroundColor Green
    } catch {
        Write-Host "Invalid OU: $ou" -ForegroundColor Red
        $errors++
    }
}

# 9. CSV Validation (Optional Input)
$csvPath = Read-Host "`n[9] Enter CSV path to validate (or press Enter to skip)"
if ($csvPath) {
    if (Test-Path $csvPath) {
        try {
            Import-Csv $csvPath | Select-Object -First 1 | Out-Null
            Write-Host "CSV format looks valid" -ForegroundColor Green
        } catch {
            Write-Host "CSV format error" -ForegroundColor Red
            $errors++
        }
    } else {
        Write-Host "CSV file not found" -ForegroundColor Red
        $errors++
    }
}

# FINAL RESULT
Write-Host "`n===== RESULT ====="
if ($errors -eq 0) {
    Write-Host "All checks passed. Safe to run AD scripts." -ForegroundColor Green
} else {
    Write-Host "$errors issue(s) found. Fix before proceeding." -ForegroundColor Red
}

Write-Host "============================================="

How to use:

Save as: AD_PreCheck.ps1

Run: .\AD_PreCheck.ps1(in PowerShell)

What this tool does

Checks admin rights
Verifies AD module
Confirms domain connection
Finds domain controller
Tests permissions
Checks execution policy
Validates time sync
Validates OU (optional)
Validates CSV (optional)



Subscribe to my YouTube channel: www.youtube.com/@Stack_Tech

Comments

Popular posts from this blog

Active Directory Overview (Windows Server) for Interview Preparation

Desktop Support Interview Q&A (Beginner Level)

IT Abbreviations Explained for Beginners | Most Asked in Interviews