PowerShell Get-ADUser, Set-ADUser, New-ADUser, Remove-ADUser
PowerShell Scripting using the Active Directory Module
Managing Active Directory (AD) users using PowerShell is a powerful way to automate and streamline administrative tasks. Key cmdlets include Get-ADUser, Set-ADUser, and New-ADUser, which allow for efficient retrieval, modification, and creation of AD user accounts. Below is a detailed guide on using these cmdlets.
​
Prerequisites
-
Correct rights in the Active Directory domain
-
PowerShell Active Directory module
More code examples below !
(Set-ADUser) - Update multiple fields within Active Directory (AD) on multiple accounts from CSV file import.
​
$All=Import-Csv C:\Temp\Book2.csv
​
ForEach($Item in $All){
$Description=$Item.Office + "," + $Item.department + "," + $Item.title
Set-ADuser $Item.SAM -title $Item.title -Department $Item.Department -Office $Item.Office -company $Item.Company -Description $Description
}
(New-ADuser) - Mass Create Users from CSV FIle Source: Includes Setting Password
$MyAccounts= Import-csv "C:\temp\Users.csv"
Foreach($Account in $MyAccounts){
$Names=($Account.Firstname)+($Account.Lastname)
New-ADUser -Name $Names -EmailAddress $Account.Email -SamAccountName $Account.Samaccount -DisplayName $Names -GivenName $Account.FirstName `
-Surname $Account.LastName -UserPrincipalName $Account.UPN -Enabled $true -ChangePasswordAtLogon $False -AccountPassword `
(ConvertTo-SecureString -AsPlainText "$($Account.PassWord)" -Force) -passthru -PasswordNeverExpires $True -CannotChangePassword $True `
-Description $Account.Description -Company "Scripts By Scott" -Path $Account.OU -ErrorAction Stop
}
(Get-ADuser) - Get Active Directory (AD) User Accounts That have Not Changed Password in over 100 Days.
$Date = [DateTime]::Today.AddDays(-100)
Get-ADUser -Filter ‘PasswordLastSet -le $Date’ -properties * | Select Name, PasswordLastSet, Enabled | Export-csv C:\temp\User.csv
​
​
​
(Get-ADuser) - Search for Active Directory Accounts where Password Setting "Never Expires" is enabled.
Get-ADuser -Properties * -filter {PasswordNeverExpires -eq $True} | Select Samaccountname, Givenname, Surname, Enabled
​
​
​
​
(Get-ADuser) - group membership for each user account listed in the source file. Note:Exports a .CSV for each user.
$users= Get-Content C:\Temp\SamAccountList.txt
foreach ($user in $users) {
$user=$user.Trim()
Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof | Out-File C:\temp\$user.csv -Append
}
​
​
​
(Get-ADuser) - Lists the info for each user account listed in the source Text file.
$Users= Get-Content C:\Temp\Accounts.txt
foreach ($user in $users) {
Get-ADuser -Properties * -filter {DisplayName -like $user} | Select Samaccountname, Givenname, Surname, Description, Enabled}
(Get-ADUser) - specifying the Ogranizational Unit (OU) Distinguished Name (DN)
Get-ADUser -filter * -searchbase "OU=MyUsers,DC=MynewForest,DC=local" | Select Name, SamAccountName
(Get-ADuser) - By First Last Name Comparison (-Like)