Streamline your AD administration with powerful PowerShell scripts
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
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"
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"
}
$InactiveDate = (Get-Date).AddDays(-90)
Get-ADUser -Filter {LastLogonDate -lt $InactiveDate -and Enabled -eq $true} -Properties LastLogonDate |
Disable-ADAccount
New-ADGroup -Name "Marketing Team" -SamAccountName "MarketingTeam" `
-GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=contoso,DC=com"
$Group = "MarketingTeam"
$Users = @("jdoe", "jsmith", "ajonhson")
$Users | ForEach-Object {
Add-ADGroupMember -Identity $Group -Members $_
}
Get-ADGroupMember -Identity "MarketingTeam" | Select-Object Name, SamAccountName
New-ADOrganizationalUnit -Name "Sales Department" -Path "DC=contoso,DC=com"
Get-ADUser -Filter {Department -eq "Sales"} |
Move-ADObject -TargetPath "OU=Sales Department,DC=contoso,DC=com"
Get-ADUser -Filter * -Properties Name, SamAccountName, Enabled, LastLogonDate |
Select-Object Name, SamAccountName, Enabled, LastLogonDate |
Export-Csv -Path "C:\UserReport.csv" -NoTypeInformation
$ExpirationDate = (Get-Date).AddDays(-90)
Get-ADComputer -Filter {LastLogonDate -lt $ExpirationDate} -Properties LastLogonDate |
Select-Object Name, LastLogonDate |
Export-Csv -Path "C:\ExpiredComputers.csv" -NoTypeInformation
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.