Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

PowerShell Script Guide: View OU Members in Active Directory

Key takeaways

  • PowerShell proficiency: Leveraging PowerShell is crucial for efficient AD management, particularly for handling user accounts in OUs.
  • Script structuring: Understanding the script’s begin, process, and end blocks is key to its operation and potential customizations.
  • Administrative access: Running the script with administrative privileges is necessary for accessing and modifying AD data.
  • Parameter flexibility: The script can be adapted to various AD environments by adjusting the OU and CustomField parameters.
  • Efficiency over tradition: PowerShell scripting offers a more efficient and automatable approach compared to traditional AD management methods.
  • Security considerations: Ensuring restricted access to the script is vital due to its capability to retrieve sensitive user information.
  • Adaptability and extension: The script’s modular nature allows for easy modifications to cater to specific AD infrastructure needs.
  • Complementary tools: Integrating PowerShell scripts with platforms like NinjaOne can enhance overall IT management and operational efficiency.

The management of Active Directory (AD) is a fundamental aspect of network administration in many corporate environments. As administrators grapple with the complexities of managing user accounts and organizational units (OUs), PowerShell emerges as a robust tool, offering both flexibility and efficiency. This blog delves into a PowerShell script designed for extracting members of an OU from AD, an operation central to effective directory management.

Background

Active Directory, the cornerstone of identity management in Windows networks, often requires administrators to handle vast numbers of user accounts organized into OUs. The script in focus here provides a streamlined approach to retrieve user data from specific OUs, a task commonly encountered by IT professionals and Managed Service Providers (MSPs). This script not only simplifies user management but also enhances monitoring and auditing capabilities within an AD environment.

The script:

#Requires -Version 4.0

<#
.SYNOPSIS
    Gets the members of an OU from AD.
.DESCRIPTION
    Gets the members of an OU(Organizational Unit) from AD(Active Directory) and can save the results to a Custom Field.

PARAMETER: -OU "Test"
    A brief explanation of the parameter.
.EXAMPLE
    -OU "Test"

    OU=Test,DC=something,DC=local 
    -----------------------------   
    [email protected]

PARAMETER: -OU "Test" -CustomField "TestOU"
    A brief explanation of the parameter.
.EXAMPLE
    -OU "Test" -CustomField "TestOU"

    OU=Test,DC=something,DC=local
    ----------------------------- 
    [email protected]

.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows Server 2012 R2 (Domain Controller's Only)
    Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [string]$OU,
    [string]$CustomField
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    if (-not (Get-Module -Name ActiveDirectory -ListAvailable)) { 
        Write-Error "RSAT is required to get the membership. Please run this on a domain controller or on a machine with RSAT installed." 
        exit 1
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    if ($env:OU -and $env:OU -notlike "null") {
        $OU = $env:OU
    }

    if ($env:CustomField -and $env:CustomField -notlike "null") {
        $CustomField = $env:CustomField
    }

    $Report = New-Object System.Collections.Generic.List[string]

    try {
        $OUPaths = Get-ADOrganizationalUnit -Filter * | Where-Object { $_.DistinguishedName -like "OU=$OU*" } | Select-Object -ExpandProperty DistinguishedName
        $OUPaths | ForEach-Object {
            $Report.Add("`n$_")

            $TitleLength = $_.Length
            $i = 1
            $Title = $Null
            while($i -le $TitleLength){
                $Title = "$Title-"
                $i++
            }
            $Report.Add($Title)

            Get-ADUser -Filter * -SearchBase $_ -ErrorAction SilentlyContinue | Select-Object -ExpandProperty UserPrincipalName -ErrorAction SilentlyContinue | ForEach-Object { $Report.Add("$_") }
        }
    }
    catch {
        Write-Error $_
        exit 1
    }

    $Report | Write-Host

    if ($CustomField) {
        Ninja-Property-Set -Name $CustomField -Value $($Report | Out-String)
    }
}
end {
    
    
    
}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script kicks off with a mandatory version check, ensuring compatibility with PowerShell 4.0 or higher. It’s structured into three parts: begin, process, and end – standard PowerShell script blocks.

  • Begin block: This initiates a prerequisite check for the Active Directory module, crucial for the script’s AD operations. An elevation check function Test-IsElevated ensures the script runs with administrative privileges, critical for accessing AD data.
  • Process block: The core operations occur here. The script accepts two parameters: OU for specifying the Organizational Unit and CustomField for optional data output customization. It dynamically adapts to environment variables for these parameters if present. The script then generates a list ($Report) to store output. Using the Get-ADOrganizationalUnit cmdlet, it retrieves the Distinguished Names of all OUs matching the specified OU parameter. For each OU found, user details (UserPrincipalName) within it are fetched using Get-ADUser and appended to the report list.
  • End block: Primarily used for cleanup and final operations, in this script, it’s left empty, indicating no specific actions upon script completion.

Potential use cases

Imagine an IT administrator needing to audit user accounts in specific OUs regularly. Using this script, they can quickly generate a list of all users in targeted OUs, facilitating efficient auditing and compliance checks.

Comparisons

Traditionally, such tasks were performed manually through the AD Users and Computers console or using basic LDAP queries. The PowerShell approach, as illustrated by this script, offers a more flexible, scriptable solution that can be automated and integrated into larger workflows.

FAQs

  • Can the script be modified for different AD structures?
    Absolutely, the script can be adapted for various AD setups by altering the OU parameter.
  • Is it necessary to run the script with administrator privileges?
    Yes, to access AD data, administrator-level access is mandatory.
  • Can the script handle multiple OUs simultaneously?
    In its current form, it’s designed for one OU at a time, but it can be extended to handle multiple OUs.

Implications

While the script enhances efficiency, there’s a security angle to consider. Ensuring that only authorized personnel have access to run such scripts is paramount, as it deals with sensitive user information.

Recommendations

  • Always run the script in a controlled environment.
  • Regularly update the script to accommodate changes in your AD infrastructure.
  • Implement logging to track the script’s usage and output.

Final thoughts

In the realm of IT, efficiency and automation are key. PowerShell scripts, like the one explored here, play a pivotal role in streamlining AD tasks. Tools like NinjaOne complement such scripts by providing a unified platform for managing IT operations, further simplifying the challenges faced by IT professionals.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).