Huge List Of PowerShell Commands for Active Directory, Office 365 and more

by Robert Allen

This is the ultimate collection of PowerShell commands for Active Directory, Office 365, Windows Server and more.

These commands will help with numerous tasks and make your life easier.

Table of Contents:

This section contains general commands for getting domain details.

View all Active Directory commands

get-command -Module ActiveDirectory

Display Basic Domain Information

Get-ADDomain

Get all Domain Controllers by Hostname and Operating

Get-ADDomainController -filter * | select hostname, operatingsystem

Get all Fine Grained Password Policies

Get-ADFineGrainedPasswordPolicy -filter *

Get Domain Default Password Policy

Gets the password policy from the logged in domain

Get-ADDefaultDomainPasswordPolicy

Backup Active Directory System State Remotely

This will back up the domain controllers system state data. Change DC-Name to your server name and change the Backup-Path. The backup path can be a local disk or a UNC path

invoke-command -ComputerName DC-Name -scriptblock {wbadmin start systemstateback up -backupTarget:"Backup-Path" -quiet}

Related: Windows CMD Commands

This section is all Active Directory user commands.

Get User and List All Properties (attributes)

Change username to the samAccountName of the account

Get-ADUser username -Properties *

Get User and List Specific Properties

Just add whatever you want to display after select

Get-ADUser username -Properties * | Select name, department, title

Get All Active Directory Users in Domain

Get-ADUser -Filter *

Get All Users From a Specific  OU

OU = the distinguished path of the OU

Get-ADUser -SearchBase “OU=ADPRO Users,dc=ad,dc=activedirectorypro.com” -Filter *

Get AD Users by Name

This command will find all users that have the word robert in the name. Just change robert to the word you want to search for.

get-Aduser -Filter {name -like "*robert*"}

Get All Disable User Accounts

Search-ADAccount -AccountDisabled | select name

Disable User Account

Disable-ADAccount -Identity rallen

Enable User Account

Enable-ADAccount -Identity rallen

Get All Accounts with Password Set to Never Expire

get-aduser -filter * -properties Name, PasswordNeverExpires | where {$_.passwordNeverExpires -eq "true" } | Select-Object DistinguishedName,Name,Enabled

Find All Locked User Accounts

Search-ADAccount -LockedOut

Unlock User Account

Unlock-ADAccount –Identity john.smith

List all Disabled User Accounts

Search-ADAccount -AccountDisabled

Force Password Change at Next Login

Set-ADUser -Identity username -ChangePasswordAtLogon $true

Move a Single User to a New OU

You will need the distinguishedName of the user and the target OU

Move-ADObject -Identity "CN=Test User (0001),OU=ADPRO Users,DC=ad,DC=activedirectorypro,DC=com" -TargetPath "OU=HR,OU=ADPRO Users,DC=ad,DC=activedirectorypro,DC=com"

Move Users to an OU from a CSV

Setup a csv with a name field and a list of the users sAmAccountNames. Then just change the target OU path.

# Specify target OU. $TargetOU = "OU=HR,OU=ADPRO Users,DC=ad,DC=activedirectorypro,DC=com" # Read user sAMAccountNames from csv file (field labeled "Name"). Import-Csv -Path Users.csv | ForEach-Object { # Retrieve DN of User. $UserDN = (Get-ADUser -Identity $_.Name).distinguishedName # Move user to target OU. Move-ADObject -Identity $UserDN -TargetPath $TargetOU }

This section list commands used for getting Active Directory group information.

Get All members Of A Security Group

Get-ADGroupMember -identity “HR Full”

Get All Security Groups

This will list all security groups in a domain

Get-ADGroup -filter *

Add User to Group

Change group-name to the AD group you want to add users to

Add-ADGroupMember -Identity group-name -Members Sser1, user2

Export Users From a Group

This will export group members to a CSV, change group-name to the group you want to export.

Get-ADGroupMember -identity “Group-name” | select name | Export-csv -path C:\OutputGroupmembers.csv -NoTypeInformation

Get Group by keyword

Find a group by keyword. Helpful if you are not sure of the name, change group-name.

get-adgroup -filter * | Where-Object {$_.name -like "*group-name*"}

Import a List of Users to a Group

$members = Import-CSV c:itadd-to-group.csv | Select-Object -ExpandProperty samaccountname Add-ADGroupMember -Identity hr-n-drive-rw -Members $members

List of commands for getting Active Directory computers.

Get All Computers

This will list all computers in the domain

Get-AdComputer -filter *

Get All Computers by Name

This will list all the computers in the domain and only display the hostname

Get-ADComputer -filter * | select name

Get All Computers from an OU

Get-ADComputer -SearchBase "OU=DN" -Filter *

Get a Count of All Computers in Domain

Get-ADComputer -filter * | measure

Get all Windows 10 Computers

Change Windows 10 to any OS you want to search for

Get-ADComputer -filter {OperatingSystem -Like '*Windows 10*'} -property * | select name, operatingsystem

Get a Count of All computers by Operating System

This will provide a count of all computers and group them by the operating system. A great command to give you a quick inventory of computers in AD.

Get-ADComputer -Filter "name -like '*'" -Properties operatingSystem | group -Property operatingSystem | Select Name,Count

Delete a single Computer

Remove-ADComputer -Identity "USER04-SRV4"

Delete a List of Computer Accounts

Add the hostnames to a text file and run the command below.

Get-Content -Path C:ComputerList.txt | Remove-ADComputer

Delete Computers From an OU

Get-ADComputer -SearchBase "OU=DN" -Filter * | Remote-ADComputer

List of commands for getting group policy details.

Get all GPO related commands

get-command -Module grouppolicy

Get all GPOs by status

get-GPO -all | select DisplayName, gpostatus

Backup all GPOs in the Domain

Backup-Gpo -All -Path E:GPObackup

Office 365 PowerShell Commands

Commands for Office 365.

Connect To Exchange Online

This will pop up and ask for credentials

$UserCredential = Get-Credential $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection Import-PSSession $Session

Force Azure Sync

This is for the azure ad sync client.

Force delta sync (only sync changes

Start-ADSyncSyncCycle -PolicyType Delta Force a full sync Start-ADSyncSyncCycle -PolicyType Initial

Get A List of All Office 365 Users

Get-MsolUser | Select DisplayName, City, Department, ObjectID

Get Full mailbox details

Get-Mailbox email-address | fl

Get Calendar Permissions

Get-MailboxFolderPermission username:calendar

Enable Remote Mailbox (Hybrid Environment)

Use this command if you have an existing on-premise user that needs an office 365 mailbox. There are other ways to do this but this creates all the attributes in the AD account.

Replace the username and the tenant fields

Enable-RemoteMailbox username -RemoteRoutingAddress "username@tenant.mail.onmicrosoft.com"

Windows Server & Client Commands

Get all Services

get-service

Get all Processes

get-process

Display Network Adapters

Gets detailed about the network adapter installed such as name,  status, speed and mac address.

get-netadapater

Restart Remote Computers

Restart-Computer -ComputerName "Server01", "Server02", "localhost"

Get Last Boot Time

This takes a few lines

$os = Get-WmiObject win32_operatingsystem $uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime) Write-Output ("Last boot: " + $os.ConvertToDateTime($os.LastBootUpTime))

You can also run this single line to get last boot time

systeminfo | more

Start a Remote Session

Use this to start an interactive session with a remote computer

Enter-PSSession -ComputerName

Read the Content of a File (Open a file)

This example shows how to read the content of the windows firewall log file

Get-Content -Path "c:windowssystem32logfilesfirewallpfirewall.log"

Copy Files & Folders

Use this command to copy an entire folder to another folder. This will copy the folder and all the sub folder/files. The -verbose command will display the results to the console.

copy-item E:\WindowsImageBackup\exchange -destination \\server1\Backups\Exchange -recurse -verbose

Basic PowerShell Commands

Get Execution Policy

get-executionpolicy

Set Execution Policy to Unrestricted

set-executionpolicy unrestricted

Show PowerShell Version

$PSVersionTable

Get help for a command

Use this to get the help information for a command

get-help command-name

Search Get Help

Use this to search the help files. This is useful if you don’t know the command or want to see if one exists.

get-help *keyword*

Get Installed Modules

Use this command to display all the installed modules on a computer

get-installedmodule

List All Available Modules

This will list all available modules on the computer.

Get-Module -ListAvailable

Exporting results to CSV

Add export-csv to the end of commands

Get-ADUser username -Properties * | Select name, department, title | export-csv c:\user.csv

Display available commands

This will display all commands that are available based on the modules that are loaded.

get-command

Find New Modules

Replace *ntfs* with the keyword you want to search for. This searches modules at https://www.powershellgallery.com/

Find-Module *ntfs*

Install a New Module

Installs modules from https://www.powershellgallery.com/

I found a module called NTFSSecurity, to install it I run this command

install-module NTFSSecurity

Recommended Tools

  • AD Cleanup Tool - Find stale and inactive user and computer accounts in Active Directory. Export, disable, move or delete the stale accounts to increase security.
  • AD User Creation Tool - Bulk import or update Active Directory user accounts. Add users to groups, import into OUs, set multiple attributes and more.
  • NTFS Permissions Tool - Scan and audit NTFS folder permissions. See which users and groups have access to what.
  • AD Reporting Tool - Over 200 reports on users, computers, groups, OUs and more. Customize reports or create your own reports with the report builder.

58 thoughts on “Huge List Of PowerShell Commands for Active Directory, Office 365 and more”

  1. Nice, thanks. Do you know how to list a users domain that they use for their login, eg: MYDOMAIN\MySamAccountId. Thanks in advance.

    It isn’t listed when using: Get-AdUser -Properties *

    Reply
  2. Doing some research in my personal time and sent this to my work email (to use at work) with a note saying the below URL is a GOLD MINE! Thank you for this as I am just 2.5 years into IT and a beginner at learning scripting. Very helpful!!!

    Reply
  3. Hello Everyone,

    We are currently cleaning our AD environment and I need a Powershell script that find AD groups that have only Disabled users as members .
    Can anyone please help me with the script

    Reply
  4. Mr. Allen,

    Thank you for sharing this amazing list of immediately usable PS commands! Some of these have been “job savers”!! #keepemcomin’

    Stay safe!

    Reply
  5. Hi,
    I need a power shell command for AD
    I want a command where I will get the members list of the specific group name
    & removing options like select user if you wish to remove from the group.

    Thanks

    Reply
  6. Is it possible to write a script in powershell that checks a certain ou periodically and sends an email of the contents?

    Reply
  7. I need to run a few commands i think then use excel.
    needing to find all clients that are members of a single group, but located in one of two OU’s rather than entire domain.
    I’m thnking exporting list of membership, then exporting list of clients in OU#1, and again for OU#2, then comparing all 3 reports to identify any clients that are both a member of the group and in OU#1 OR OU#2

    Reply
  8. Dear, No doubt its a an incredible list, collection of useful commands. I need your kind advise. I need to know where a particular user has logged in ( I mean the computer name) the network lastly.
    Thanks in Advance

    Reply
  9. I am having trouble figuring out how to use PowerShell to batch change the Active Directory domain for a collection of users. The company went through a name change, and I need to make this modification. Can anyone help me?

    Reply
  10. Awesome, I am looking for a script which can help me to delete CNF entries. Can some help me to get any command or script which will help me to fulfil this requirement?

    Reply
  11. Hi,
    Do you know of a way to extract SYSTEM accounts via PS from Active Directory. Example RPCservice.
    get-aduser doesn’t seem to list them
    The below list them, but also regular account. I need only SYSTEM accounts and also some values from them.
    get-wmiobject -class “win32_account” -namespace “root\cimv2” | sort caption | format-table caption, __CLASS, FullName

    Reply
  12. Hi Guys

    I am new to powershell and trying to do basic things.

    Please can you help, I will greatly appreciate it

    How would I push an address say for example the address is ” 10 xyz street” across to an entire OU, lets call the OU Test?

    I need to push different addresses across multiple OUS

    Regards
    Daylon

    Reply
  13. Very good commands. I am looking for a command that lists the logon history of all users who opened their windows session. i have active directory 2008. i dont have third party tools.

    Reply
    • What do you mean opened their windows session?

      Getting logon history is difficult because the real logon event is stored on the local computer, not ain Active Directory.

      Reply
  14. Hello
    Its really very useful. Thank you. I have one query. Please help me.
    I want to add only member server (Without Domain Controller) to particular OU
    (OR)
    Please provide a script for removing Domain Controller (Not member server) from OU.
    Thanks in advance
    Regards
    Leo.

    Reply
    • Your DC’s should stay in the Domain Controllers OU.

      You can move objects with the move-adobject cmdlet. Use the distinguished name of the object you want to move then the DN of the path. Example below. This would move PC1 from the default OU to OU Accounting.

      Move-ADObject -Identity “CN=PC1,CN=Computers,DC=ad,DC=activedirectorypro,DC=com” -TargetPath “OU=Accounting,OU=ADPRO Computers,DC=ad,DC=activedirectorypro,DC=com”

      Reply
  15. Awesome, I am looking for a script which will give output of all computers in the AD with SMTP service status.

    Reply
  16. I don’t know who wrote this awesome list of PS scripts but they deserve a RAISE, a toast of glasses, a high-five with elbows (during Covid-19) a standing ovation, and a big bear hug!!! Thank you so much from the bottom of my heart ❤!!!! You ROCK, John.

    Reply
  17. A better job needs to be done in the formatting. For example

    Get-ADUser username -Properties * | Select name, department, title

    should be shown as
    Get-ADUser [username] -Properties * | Select name, department, title

    So a person knows to put in a specific name in place of [username] otherwise people think it’s part of the command string.

    Reply
  18. Hello Sir

    Thank you for this amazing list.

    I am having problems finding the size of all folders on a user C drive as well as the size of all folders on a users desktop. I have until now tried several commands but yet to receive the desired result.

    For exampe to display the folders on the C drive used this: get-childitem -force | select fullname

    To display the folders size :

    get-childitem -force | select fullname | select @{l=’Size’; e={$fso.GetFolder($_.FullName).Size}},FullName `
    | sort Size -Descending `
    | ft @{l=’Size [MB]’; e={‘{0:N2} ‘ -f ($_.Size / 1MB)}},FullName

    It displays the folders and also show the sizes unfortunately, it does not show all folder sizes only the first two folders.
    I will be very happy if you would look at the code and please asist me with it. (Powershell)

    Best regards
    Boima

    Reply
  19. Great job and thanks for the list, I’m searching for a script to extend the expiration date for a User Account NOT TO SET TO PASSWORDNOTREQUIRED OR PASSWORDNEVEREXPIRE . Kindly help me out?

    THANK YOU.

    Reply
    • $gebruiker = Read-Host -Prompt “Give username..”
      Get-ADUser $gebruiker –Properties “DisplayName”, pwdLastSet, “msDS-UserPasswordExpiryTimeComputed” |Select-Object -Property “Displayname”,@{Name=”ExpiryDate”;Expression={[datetime]::FromFileTime($_.”msDS-UserPasswordExpiryTimeComputed”)}}

      $User = Get-ADUser $gebruiker -properties “pwdlastset”
      $User.pwdlastset = 0
      Set-ADUser -Instance $User
      $user.pwdlastset = -1
      Set-ADUser -instance $User

      Get-ADUser $gebruiker –Properties “DisplayName”, pwdLastSet, “msDS-UserPasswordExpiryTimeComputed” |Select-Object -Property “Displayname”,@{Name=”ExpiryDate”;Expression={[datetime]::FromFileTime($_.”msDS-UserPasswordExpiryTimeComputed”)}}

      Reply
  20. Great info on here Robert, amazing stuff! I’m looking to export a list of all accounts where interactive logon has been enabled (or disabled, whichever is easier) – basically to test whether a service or non-corporate account is accessible by a human. Is there a powershell script that does this for me? I would hope yes!

    Reply
  21. Hi Rob
    Incredibly useful list, thanks – I’ve been trying to analyze disabled user accounts on AD; what I saw was the export for disabled accounts didn’t contain a few corporate IDs I know are disabled (they also have UserAccountControl 514, which I understand indicates a disabled account). So i’m questioning the completeness of the export I’ve got – any ideas why this might be the case? Is it possible for a few disabled accounts to not show up in an export of disabled AD accounts (admittedly these are quite few in number but I wanted to check regardless). thanks.
    VS.

    Reply
  22. This is very useful, am trying to get the users of an OU, with Name,Lastlogged on to, Email memberships, Group policy

    Reply
  23. Omg thank you so much; Now all I need to do is figure out how to get power shell to grab history and list every change its ever made.. if its possible. I hope it can. I’m trying to look for tampering on my laptop by someone using PS. I know it’s been done but how, where, the extents – hell even my registry has become questionable.

    Reply
  24. Thanks for the list, I’m looking for a script to show logged in users per server showing user name, computer name and IP address. You have anything like that yet?

    Reply

Leave a Comment