Introduction:

This post outlines a PowerShell script designed to export Organizational Units (OUs) from Active Directory into a CSV file. This can be particularly useful for administrators needing a detailed list of OUs for auditing or documentation purposes.

Description:

The script connects to a specified domain controller and retrieves the distinguished names of all OUs in the Active Directory. It then organizes these names into a structured CSV format for easy review and analysis. The output file is saved to a specified location on the user’s machine.

How to Use:

To use this script, update the placeholders with your specific Active Directory domain information, output file path, and domain controller name. Run the script in a PowerShell session with appropriate administrative privileges.

What It Does:

This script automates the process of gathering OU information from Active Directory, splitting the distinguished names into individual OU segments, and exporting the data to a CSV file for further use.

# Import the Active Directory module
Import-Module ActiveDirectory

# Define the search base (root) of the Active Directory
$searchBase = ""

# Define the output CSV file path
$outputFile = ""

# Define the desired OU properties to retrieve
$ouProperties = "DistinguishedName"

# Specify a domain controller to connect to
$domainController = ""  # Replace with the hostname of a reachable domain controller

# Perform the search for organizational units
$ous = Get-ADOrganizationalUnit -Filter 'objectClass -eq "organizationalUnit"' -SearchBase $searchBase -Properties $ouProperties -Server $domainController

# Create a custom object to hold the OU information
$ouList = foreach ($ou in $ous) {
    $ouDN = $ou.DistinguishedName
    $ouSegments = $ouDN -split ',OU=' | Select-Object -Skip 1
    $ouProps = [ordered]@{
        "DistinguishedName" = $ouDN
    }
    for ($i = 0; $i -lt $ouSegments.Count; $i++) {
        $columnName = "OU$($i + 1)"
        $ouProps[$columnName] = $ouSegments[$i] -replace '^OU=', ''
    }
    [PSCustomObject]$ouProps
}

# Export the OU information to a CSV file
$ouList | Export-Csv -Path $outputFile -NoTypeInformation

Tags: #ActiveDirectory #PowerShell #OUExport #CSV #ITAutomation