0
0
PowerShellscripting~7 mins

Organizational unit operations in PowerShell

Choose your learning style9 modes available
Introduction
Organizational units (OUs) help organize users and computers in a network. Managing OUs with scripts saves time and keeps things tidy.
You want to create a new OU for a department in your company.
You need to move users or computers into a specific OU automatically.
You want to delete an OU that is no longer needed.
You want to list all OUs in your Active Directory to check the structure.
You want to rename an OU to reflect a new department name.
Syntax
PowerShell
New-ADOrganizationalUnit -Name <string> [-Path <string>] [-Description <string>]
Get-ADOrganizationalUnit [-Filter <string>] [-SearchBase <string>]
Remove-ADOrganizationalUnit -Identity <string> [-Confirm]
Rename-ADObject -Identity <string> -NewName <string>
Move-ADObject -Identity <string> -TargetPath <string>
Use the Active Directory module in PowerShell to run these commands.
You need appropriate permissions to manage OUs in your domain.
Examples
Creates a new OU named 'Sales' with a description.
PowerShell
New-ADOrganizationalUnit -Name "Sales" -Description "Sales Department OU"
Lists all organizational units in the domain.
PowerShell
Get-ADOrganizationalUnit -Filter *
Deletes the OU named 'OldDept' without asking for confirmation.
PowerShell
Remove-ADOrganizationalUnit -Identity "OU=OldDept,DC=example,DC=com" -Confirm:$false
Renames the OU 'Marketing' to 'GlobalMarketing'.
PowerShell
Rename-ADObject -Identity "OU=Marketing,DC=example,DC=com" -NewName "GlobalMarketing"
Sample Program
This script shows how to create, list, rename, and delete an OU step-by-step.
PowerShell
Import-Module ActiveDirectory

# Create a new OU called 'HR'
New-ADOrganizationalUnit -Name "HR" -Description "Human Resources Department"

# List all OUs to confirm creation
Get-ADOrganizationalUnit -Filter * | Select-Object Name

# Rename the 'HR' OU to 'HumanResources'
Rename-ADObject -Identity "OU=HR,DC=example,DC=com" -NewName "HumanResources"

# List all OUs again to see the change
Get-ADOrganizationalUnit -Filter * | Select-Object Name

# Remove the 'HumanResources' OU
Remove-ADOrganizationalUnit -Identity "OU=HumanResources,DC=example,DC=com" -Confirm:$false

# List all OUs to confirm removal
Get-ADOrganizationalUnit -Filter * | Select-Object Name
OutputSuccess
Important Notes
Always check your OU paths carefully to avoid deleting the wrong OU.
Use -Confirm:$false to skip confirmation prompts in scripts, but be cautious.
You can filter OUs by name or path using the -Filter and -SearchBase parameters.
Summary
Organizational units help organize network resources.
PowerShell commands let you create, list, rename, move, and delete OUs.
Scripts save time and reduce errors when managing many OUs.