PowerShell Scripting for Active Directory Management

Streamline your AD administration with powerful PowerShell scripts

1. Getting Started with Active Directory PowerShell Module

Before you begin, make sure you have the Active Directory module installed and imported:

Import-Module ActiveDirectory

To verify the module is loaded, you can run:

Get-Module -Name ActiveDirectory

2. User Management Scripts

Creating a New User

New-ADUser -Name "John Doe" -SamAccountName "jdoe" -UserPrincipalName "[email protected]" `
    -GivenName "John" -Surname "Doe" -Enabled $true -ChangePasswordAtLogon $true `
    -AccountPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) `
    -Path "OU=Users,DC=contoso,DC=com"

Bulk User Creation from CSV

Import-Csv "C:\Users.csv" | ForEach-Object {
    New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName `
        -UserPrincipalName "$($_.SamAccountName)@contoso.com" `
        -GivenName $_.GivenName -Surname $_.Surname -Enabled $true `
        -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) `
        -Path "OU=Users,DC=contoso,DC=com"
}

Disabling Inactive Users

$InactiveDate = (Get-Date).AddDays(-90)
Get-ADUser -Filter {LastLogonDate -lt $InactiveDate -and Enabled -eq $true} -Properties LastLogonDate |
    Disable-ADAccount

3. Group Management Scripts

Creating a New Security Group

New-ADGroup -Name "Marketing Team" -SamAccountName "MarketingTeam" `
    -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=contoso,DC=com"

Adding Users to a Group

$Group = "MarketingTeam"
$Users = @("jdoe", "jsmith", "ajonhson")
$Users | ForEach-Object {
    Add-ADGroupMember -Identity $Group -Members $_
}

Listing Group Members

Get-ADGroupMember -Identity "MarketingTeam" | Select-Object Name, SamAccountName

4. Organizational Unit (OU) Management

Creating a New OU

New-ADOrganizationalUnit -Name "Sales Department" -Path "DC=contoso,DC=com"

Moving Objects to an OU

Get-ADUser -Filter {Department -eq "Sales"} |
    Move-ADObject -TargetPath "OU=Sales Department,DC=contoso,DC=com"

5. Reporting Scripts

Generate User Account Report

Get-ADUser -Filter * -Properties Name, SamAccountName, Enabled, LastLogonDate |
    Select-Object Name, SamAccountName, Enabled, LastLogonDate |
    Export-Csv -Path "C:\UserReport.csv" -NoTypeInformation

Find Expired Computer Accounts

$ExpirationDate = (Get-Date).AddDays(-90)
Get-ADComputer -Filter {LastLogonDate -lt $ExpirationDate} -Properties LastLogonDate |
    Select-Object Name, LastLogonDate |
    Export-Csv -Path "C:\ExpiredComputers.csv" -NoTypeInformation

Note:

Always test your scripts in a non-production environment before running them on your live Active Directory. Make sure you have the necessary permissions to execute these commands.






Scroll to Top