PowerShell OneLiners for Active Directory

Active Directory is the backbone of many modern enterprise environments—a centralized platform for managing user accounts, groups, computers, and other resources. With PowerShell OneLiners, managing AD has never been more accessible. PowerShell is a powerful command-line tool that can help automate many tasks related to AD management.

This blog post will cover some of the most useful PowerShell oneliners for effective AD management.

You may want to create some random users to test these commands out. Here is a oneliner to create 20 random users:

PowerShell
1..20 | ForEach-Object { New-ADUser -Name ("User" + $_) -SamAccountName ("User" + $_) -AccountPassword (ConvertTo-SecureString "Password123!" -AsPlainText -Force) -Enabled $true -EmailAddress ("User" + $_ + "@turbogeek.co.uk") -GivenName (Get-Random -InputObject @("Alice", "Bob", "Charlie", "David", "Eva", "Frank", "Grace", "Henry", "Iris", "Jack")) -Surname (Get-Random -InputObject @("Smith", "Johnson", "Brown", "Lee", "Garcia", "Martinez", "Davis", "Taylor", "Wilson", "Anderson")) -StreetAddress (Get-Random -InputObject @("123 Main St.", "456 Elm St.", "789 Oak Ave.", "321 Pine St.", "654 Maple Ave.")) -City (Get-Random -InputObject @("New York", "Los Angeles", "Chicago", "Houston", "Philadelphia", "Phoenix", "San Antonio", "San Diego", "Dallas", "San Jose")) -State (Get-Random -InputObject @("CA", "TX", "NY", "FL", "IL", "PA", "OH", "GA", "NC", "MI")) -PostalCode (Get-Random -InputObject @(10001..99999)) }

https://www.turbogeek.co.uk/how-to-upgrade-a-windows-server-2003-domain-to-windows-server-2016/

Get-ADUser

PowerShell One-Liners for Active Directory: The Basics

Get-ADUser is a PowerShell cmdlet that retrieves user accounts from AD. This cmdlet can search for user accounts based on various criteria such as username, email, department, etc. Here are some examples:


Retrieve all user accounts in the domain

PowerShell
Get-ADUser -Filter * 

Get all user accounts in the Marketing department.

PowerShell
Get-ADUser -Filter 'Department -eq "Marketing"' 

Recover a specific user account by username.

PowerShell
Get-ADUser -Identity "jdoe" 

Get-ADUser is a powerful cmdlet that can help you quickly retrieve user accounts from Active Directory.

PowerShell One-Liners for Active Directory: Complex Oneliners


Retrieve all users who have not logged in for the past 90 days

PowerShell
Get-ADUser -Filter {LastLogonTimeStamp -lt (Get-Date).AddDays(-90)} -Properties LastLogonTimeStamp | Select Name, SamAccountName, LastLogonTimeStamp | Sort-Object LastLogonTimeStamp

Get-ADComputer

Basic Commands

Get-ADComputer is a PowerShell cmdlet that retrieves computer accounts from A. This cmdlet can search for computer accounts based on criteria such as name, operating system, etc. Here are some examples:

Retrieve all computer accounts in the domain.

PowerShell
Get-ADComputer - 

Discover all computer accounts running Windows 10

PowerShell
Get-ADComputer -Filter 'OperatingSystem -like "Windows 10*"' 

Get a specific computer account by name

PowerShell
Get-ADComputer -Identity "computer01" 

Get-ADComputer is a useful cmdlet for managing computer accounts in Active Directory.


New-ADUser

ADUser is a PowerShell cmdlet that creates a new user account in AD This cmdlet can specify various properties for the new user account, such as name, password, department, and more.

Here are some examples:

Example 1: Create a new user account with default settings

PowerShell
<code>New-ADUser -Name "John Doe" -SamAccountName "jdoe" -AccountPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) </code>

Example 2: Create a new user account with custom settings

PowerShell
<code>New-ADUser -Name "Jane Smith" -SamAccountName "jsmith" -AccountPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) -Department "Marketing" -EmailAddress "[email protected]" </code>

New-ADUser is a powerful cmdlet that can quickly help you create new user accounts in Active Directory.


New-ADGroup

New-ADGroup is a PowerShell cmdlet that creates a new group in AD. This cmdlet can specify various properties for the new group, such as name, description, and more. Here are some examples:

Example 1: Create a new group with default settings

PowerShell
New-ADGroup -Name "Marketing" 

Example 2: Create a with custom settings

PowerShell
New-ADGroup -Name "Sales" -Description "Group for sales department" 

New-ADGroup is a useful cmdlet for creating new groups in Active Directory.


Add-ADGroupMember

Add-ADGroupMember is a PowerShell cmdlet that adds a member to an AD group. This cmdlet can add users or other groups as group members. Here are some examples:

Example 1: Add a user to a group

PowerShell
Add-ADGroupMember -Identity "Marketing" -Members "jdoe" 

Example 2: Add a group to another group

PowerShell
Add-ADGroupMember -Identity "Sales" -Members "Marketing" 

Add-ADGroupMember is a useful cmdlet for managing group membership in Active Directory.


Remove-ADGroupMember

Remove-ADGroupMember is a PowerShell cmdlet that removes a member from an AD group. This cmdlet can remove users or other groups as group members. Here are some examples:

Example 1: Remove a user from a group

PowerShell
Remove-ADGroupMember -Identity "Marketing" -Members "jdoe" 

Example 2: Remove a group from another group

PowerShell
Remove-ADGroupMember -Identity "Sales" -Members "Marketing" 

Remove-ADGroupMember is a useful cmdlet for managing group membership in Active Directory.


Set-ADUser

Set-ADUser is a PowerShell cmdlet that modifies the properties of an existing user account in Active Directory. This cmdlet can change various properties such as name, department, email, etc. Here are some examples:

Example 1: Change the department of a user

PowerShell
Set-ADUser -Identity "jdoe" -Department "Sales" 

Example 2: Change the email address of a user

PowerShell
Set-ADUser -Identity "jdoe" -EmailAddress "[email protected]" 

Set-ADUser is a powerful cmdlet for modifying user accounts in Active Directory.

PowerShell is a powerful tool for managing Active Directory more efficiently and effectively. Using the cmdlets we have covered in this post, you can quickly retrieve user and computer accounts, create new user accounts and groups, manage group membership, and modify user account properties. With PowerShell, you can automate many routine tasks related to Active Directory management, saving time and reducing errors.


Further Examples of PowerShell Oneliners

List all users in a specific Active Directory group:

PowerShell
Get-ADGroupMember -Identity "GroupName" | Select-Object Name


Find all disabled user accounts in Active Directory:

PowerShell
Get-ADUser -Filter 'Enabled -eq $false' -Properties Name, SamAccountName


List all active users in a specific Organizational Unit (OU) in Active Directory:

PowerShell
Get-ADUser -Filter 'Enabled -eq $true' -SearchBase "OU=OUName,DC=DomainName,DC=com" | Select-Object Name, SamAccountName


Create a new Active Directory user account with a specified password:

PowerShell
New-ADUser -Name "UserName" -UserPrincipalName "[email protected]" -AccountPassword (ConvertTo-SecureString "Password123" -AsPlainText -Force) -Enabled $true -Path "OU=OUName,DC=DomainName,DC=com"


Set the account expiration date for an Active Directory user account:

PowerShell
Set-ADUser -Identity "UserName" -AccountExpirationDate "mm/dd/yyyy"


Find all Active Directory user accounts that have not logged in within a limited number of days:

PowerShell
Search-ADAccount -UsersOnly -AccountInactive -TimeSpan "30.00:00:00" | Select-Object Name, SamAccountName


Enable a disabled Active Directory user account:

PowerShell
Enable-ADAccount -Identity "UserName"

Reset the password for an Active Directory user account:

PowerShell
Set-ADAccountPassword -Identity "UserName" -NewPassword (ConvertTo-SecureString "NewPassword123" -AsPlainText -Force) -Reset

Find all Active Directory groups that a specific user is a member of:

PowerShell
Get-ADPrincipalGroupMembership -Identity "UserName" | Select-Object Name


Remove a user from an Active Directory group:

PowerShell
Remove-ADGroupMember -Identity "GroupName" -Members "UserName"


Resetting passwords for multiple users in one line:

PowerShell
Get-ADUser -Filter * | ForEach-Object {Set-ADAccountPassword $_ -NewPassword (ConvertTo-SecureString "Password1234!" -AsPlainText -Force)}

This will get all AD users and set their password to “Password1234!”.

Elsewhere On TurboGeek:  Terraform in Azure

Finding all users who haven’t changed their password in a while:

PowerShell
Get-ADUser -Filter * -Properties PasswordLastSet, PasswordNeverExpires | Where-Object {$_.PasswordLastSet -lt (Get-Date).AddDays(-90) -and $_.Enabled -eq $True -and $_.PasswordNeverExpires -eq $False} | Select-Object Name, SamAccountName, PasswordLastSet

This will find all users whose password was last set more than 90 days ago, are currently enabled, and whose password doesn’t ever expire. It will also display their name, account name, and the date their password was last set.


Creating a new user with multiple attributes set:

PowerShell
New-ADUser -Name "John Smith" -GivenName "John" -Surname "Smith" -SamAccountName "jsmith" -UserPrincipalName "[email protected]" -AccountPassword (ConvertTo-SecureString "Password1234!" -AsPlainText -Force) -Enabled $True -Path "OU=Users,OU=Contoso,DC=Contoso,DC=com"

This will create a new user named “John Smith” with the account name “jsmith”. It will set their password to “Password1234!” and enable the account. The user will be created in the “Users” OU within the “Contoso” domain.


Removing all members from a group except for a specified user:

PowerShell
Get-ADGroupMember -Identity "GroupName" | Where-Object {$_.SamAccountName -ne "Username"} | ForEach-Object {Remove-ADGroupMember -Identity "GroupName" -Members $_ -Confirm:$False}

This will get all members of a group named “GroupName” and remove all of them except for the user named “Username”.

Note: These oneliners can be pretty powerful and potentially destructive if misused. It’s essential to test them thoroughly in a non-production environment before running them in a production environment.


FAQ on PowerShell OneLiners for Active Directory

What are PowerShell One-Liners?

PowerShell One-Liners are commands that can be run in a single line of code in PowerShell. They are often used to perform quick tasks or to automate repetitive tasks in Active Directory.

Why should I use PowerShell OneLiners for Active Directory?

PowerShell One-Liners can save you time and effort when managing Active Directory. With just one line of code, you can perform tasks that would otherwise take multiple clicks or commands.

Can I use PowerShell OneLiners to manage multiple Active Directory domains?

Yes, PowerShell One-Liners can be used to manage multiple Active Directory domains. When running the command, you just need to specify the appropriate domain controller or forest.

What permissions do I need to run PowerShell OneLiners for Active Directory?

You need to have the appropriate permissions to manage Active Directory objects to run PowerShell One-Liners. This usually means being a member of the Domain Admins group or having delegated permissions.

Can I use PowerShell OneLiners to create new Active Directory objects?

Yes, PowerShell One-Liners can be used to create new Active Directory objects, such as user accounts, group accounts, and computer accounts.

How do I find specific Active Directory objects using PowerShell OneLiners?

You can use PowerShell One-Liners to search for specific Active Directory objects based on criteria such as name, description, or group membership. The Get-ADObject and Get-ADUser commands are often used for this purpose.

Can I use PowerShell OneLiners to modify existing Active Directory objects?

Yes, PowerShell One-Liners can be used to modify existing Active Directory objects, such as changing a user’s group membership or resetting a user’s password.

How do I delete Active Directory objects using PowerShell OneLiners?

You can use PowerShell One-Liners to delete Active Directory objects, such as user accounts or group accounts, using commands such as Remove-ADUser and Remove-ADGroup.

Can I use PowerShell OneLiners to generate reports or export data from Active Directory?

Yes, PowerShell One-Liners can be used to generate reports or export data from Active Directory. The Get-ADUser, Get-ADGroup, and Get-ADComputer commands can be used to retrieve information about Active Directory objects, which can then be formatted and exported using other PowerShell commands.

Where can I find examples of PowerShell OneLiners for Active Directory?

You can find examples of PowerShell One-Liners for Active Directory on various blogs and forums and in Microsoft’s official documentation. You can also create your own One-Liners to automate tasks specific to your environment.

Richard.Bailey

Richard Bailey, a seasoned tech enthusiast, combines a passion for innovation with a knack for simplifying complex concepts. With over a decade in the industry, he's pioneered transformative solutions, blending creativity with technical prowess. An avid writer, Richard's articles resonate with readers, offering insightful perspectives that bridge the gap between technology and everyday life. His commitment to excellence and tireless pursuit of knowledge continues to inspire and shape the tech landscape.

You may also like...

2 Responses

  1. 05/09/2023

    […] to get you started. All these steps can be completed using PowerShell; look out for the PowerShell […]

  2. 10/10/2023

    […] Active Directory Oneliners […]

Leave a Reply

Your email address will not be published. Required fields are marked *