Powershell ad script

Powershell ad script DEFAULT

How to Create New Active Directory Users with PowerShell

The easiest way to create a new user in an Active Directory domain is using the Active Directory Users and Computers MMC snap-in. However, what if you need to create multiple user accounts in bulk, or ADUC is not available for some reason? In this article, we explain several ways to create Active Directory user accounts with PowerShell using the New-ADUser cmdlet.

Create New User Accounts using the New-ADUser Cmdlet

So what is the PowerShell cmdlet used to create user objects? It’s the New-ADUser cmdlet, which is included in the Active Directory PowerShell module built into Microsoft Windows Server 2008R2/2012 and above. Therefore, the first thing we need to do is enable the AD module:

Import-Module ActiveDirectory

Now let’s take a closer look at cmdlet New-ADUser. We can get its full syntax by running the following command:

Get-Command New-ADUser –Syntax

Create New User Accounts in Active Directory using the New-ADUser Cmdlet

When you know the syntax, it’s easy to add users to Active Directory:

New-ADUser B.Johnson

Now let’s check whether the user was added successfully by listing all Active Directory users using the following script:

Get-ADUser -Filter * -Properties samAccountName | select samAccountName

Create New User Accounts using the New-ADUser Cmdlet Check

There it is, the last one in the list!

Create a New Active Directory User Account with Password

Accounts are created with the following default properties:

  • Account is created in the “Users” container.
  • Account is disabled.
  • Account is a member of Domain Users group.
  • No password is set.
  • User must reset the password at the first logon.

Therefore, to make a new account that’s actually usable, we need to enable it using the Enable-ADAccount cmdlet and give it a password using the Set-ADAccountPassword cmdlet.

So let’s create a new account with the following attributes:

  • Name – Jack Robinson
  • Given Name – Jack
  • Surname – Robinson
  • Account Name – J.Robinson
  • User Principal Name[email protected]
  • Path address – “OU=Managers,DC=enterprise,DC=com”
  • Password Input
  • Status – Enabled

Here’s the script we’ll use:

New-ADUser -Name "Jack Robinson" -GivenName "Jack" -Surname "Robinson" -SamAccountName "J.Robinson" -UserPrincipalName "[email protected]" -Path "OU=Managers,DC=enterprise,DC=com" -AccountPassword(Read-Host -AsSecureString "Input Password") -Enabled $true

The Read-Host parameter will ask you to input new password. Note that the password should meet the length, complexity and history requirements of your domain security policy.

Now let’s take a look at the results by running the following cmdlet:

Get-ADUser J.Robinson -Properties CanonicalName, Enabled, GivenName, Surname, Name, UserPrincipalName, samAccountName, whenCreated, PasswordLastSet  | Select CanonicalName, Enabled, GivenName, Surname, Name, UserPrincipalName, samAccountName, whenCreated, PasswordLastSet

Create a New Active Directory User Account with Password

Create AD Users in Bulk with a PowerShell Script

Now, let’s make our task a little bit harder and create ten similar Active Directory accounts in bulk, for example, for our company’s IT class, and set a default password ([email protected]) for each of them. To send the default password in a protected state, we must use the ConvertTo-SecureString parameter. Here’s the script to use:

$path="OU=IT,DC=enterprise,DC=com" $username="ITclassuser" $count=1..10 foreach ($i in $count) { New-AdUser -Name $username$i -Path $path -Enabled $True -ChangePasswordAtLogon $true  ` -AccountPassword (ConvertTo-SecureString "[email protected]" -AsPlainText -force) -passThru }

Create Active Directory Users in Bulk with a PowerShell Script

Now let’s make our script more flexible by adding the Read-Host parameter, which will ask for the name and number of users:

$path="OU=IT,DC=enterprise,DC=com" $username=Read-Host "Enter name" $n=Read-Host "Enter Number" $count=1..$n foreach ($i in $count) { New-AdUser -Name $username$i -Path $path -Enabled $True -ChangePasswordAtLogon $true  ` -AccountPassword (ConvertTo-SecureString "[email protected]" -AsPlainText -force) -passThru }

Create Active Directory Users in Bulk with a PowerShell Script

Import AD Users from a CSV File

Another option for creating users in AD is to import them from a CSV file. This option is great when you have a list of users with predefined personal details such as:

  • FirstName
  • LastName
  • Username
  • Department
  • Password
  • OU

The CSV file must be in UTF8 encoding and contain contact data that looks like this:

Import Active Directory Users from a CSV File


The following script will create enabled user objects for any users in the CSV that don’t already have accounts in AD. The “Reset password at the next logon” option will be enabled for the new accounts, so you can use your default password:

#Enter a path to your import CSV file $ADUsers = Import-csv C:\scripts\newusers.csv foreach ($User in $ADUsers) {        $Username    = $User.username        $Password    = $User.password        $Firstname   = $User.firstname        $Lastname    = $User.lastname     $Department = $User.department        $OU           = $User.ou        #Check if the user account already exists in AD        if (Get-ADUser -F {SamAccountName -eq $Username})        {                #If user does exist, output a warning message                Write-Warning "A user account $Username has already exist in Active Directory."        }        else        {               #If a user does not exist then create a new user account                    #Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable               New-ADUser `             -SamAccountName $Username `             -UserPrincipalName "[email protected]" `             -Name "$Firstname $Lastname" `             -GivenName $Firstname `             -Surname $Lastname `             -Enabled $True `             -ChangePasswordAtLogon $True `             -DisplayName "$Lastname, $Firstname" `             -Department $Department `             -Path $OU `             -AccountPassword (convertto-securestring $Password -AsPlainText -Force)        } }

After script execution, we have two new users, Edward Franklin and Bill Jackson, in our Active Directory domain:

Import Active Directory Users from a CSV File after script execution

Let’s take a look at their details by running Get-ADUser cmdlet again:

Get-ADUser E.Franklin -Properties CanonicalName, Enabled, GivenName, Surname, Name, UserPrincipalName, samAccountName, whenCreated, PasswordLastSet  | Select CanonicalName, Enabled, GivenName, Surname, Name, UserPrincipalName, samAccountName, whenCreated, PasswordLastSet


Now you know how to create users in Active Directory using PowerShell scripts. Try performing some account creations, bulk account creations and CSV imports yourself on local or remote systems. Remember, the ADUC MMC snap-in is great for creating a few users with extended attributes, but PowerShell is much better for importing a large number of user accounts in bulk.

Jeff Melnick

Jeff is a former Director of Global Solutions Engineering at Netwrix. He is a long-time Netwrix blogger, speaker, and presenter. In the Netwrix blog, Jeff shares lifehacks, tips and tricks that can dramatically improve your system administration experience.

Sours: https://blog.netwrix.com/2018/06/07/how-to-create-new-active-directory-users-with-powershell/

PowerShell for AD user reports

Real-time insights on user account status and activity can help AD  administrators manage accounts better. Many administrators use Microsoft's PowerShell scripts to generate Active Directory reports  and pull detailed information. Below are some key Active Directory PowerShell scripts and commands for generating AD user reports. Further below, you'll find a tool that makes AD User reporting  even easier by helping you generate those AD reports in a cinch from  an intuitive, unified web-console.

All users reports

Get-ADUser -Filter * -Properties * | Export-csv -path "c:\testexport.csv

Disabled users report

Get-ADUser -Filter 'enabled -eq $False'| fl name,samaccountname,surname,userprincipalname

O365 All users report

Import-module msonline
# Supply the Office365 domain credentials
$username = "[email protected]"
$password = ConvertTo-SecureString -String "[email protected]" -AsPlainText -Force
$cred = New-object -typename
System.Management.Automation.PSCredential-argumentlist $username, $password
Connect-MsolService -credential $cred

O365 licensed users report

Get-ADUser -Filter * -Properties * | Export-csv -path "c:\testexport.csv

OU specific reports

Get-ADOrganizationalUnit -Filter * | fl name,DistinguishedName

Account status reports

Get-ADUser -Filter * | fl name,enabled

PowerShell searching

Get-ADUser -Filter 'SearchQuery', For example "Get-ADUser -Filter 'enabled -eq $

The ADManager Plus way

In organizations, it's a rarity that we come across such simple straightforward scenarios like the ones listed above. Real-life use cases involve a multitude of things. Often, administrators need to program extensively in PowerShell, research syntax, and iterate multiple times for correctness; all these tasks can turn into a nightmare for administrators. PowerShell scripts for Active Directory sure is empowering, but at what cost? Often, the cost of extensive scripting is prolonged work hours.

The biggest limitation to PowerShell reports is that they aren't actionable. AD admins need to get work done from a single window without having to toggle between multiple consoles.

Here's how you can save yourself from the burden and monotony of creating, testing and executing unending lines of PowerShell scripts to generate reports on AD user accounts.

User reports from ADManager Plus give complete insight into the Windows Active Directory domain. ADManager Plus makes generating reports a breeze, even for organizations with multiple domains, organizational units (OUs) and numerous users.

ADManager Plus offers a comprehensive list of pre-built Active Directory user reports, for efficient, trouble-free management and reporting on user accounts. Other key advantages include:

  • Fully web-based, intuitive UI that lets you customize required reporting fields
  • Option to schedule reports and automate report generation
  • OU specific report generation
  • Export reports in various formats: CSV, Excel, PDF, HTML, and CSVDE
  • Compliance-based reports (SOX, HIPAA, etc)

User reports are important to get vital information, including which users have remote user logon permissions or are mailbox enabled, or have OMA/OWA enabled.  ADManager Plus features an array of  schedulable reports on user objects, categorized into General User Reports, User Account Status Reports, User Logon Reports, and Nested Users Reports.

User Logon reports offers a peek into the user logon history or information. AD admins can generate reports on inactive users�(users who have not logged on for a certain period), users who have logged on recently, users who have never logged on, and enabled users. The logon hour based report shows�the allowed and denied logon hours or time frame for users.

Admins can decipher fine-grained group membership information from the Nested Users Report. These reports display detailed information about users in a particular group and the multiple groups a user belongs to.

Actionable User Reports

Say you are planning to delete inactive accounts from a specific department. If you are planning to get this done using native Active Directory tools and PowerShell, this could take you a day or more. After multiple iterations, you might be able to finally script what you need.

On the other hand, ADManager Plus gives you the liberty of carrying out the same task with just a few clicks. Run the Inactive users report, specify the desired OU using the smart filter, and delete inactive users all from the same screen.

Thus ADManager Plus easily addresses the AD reporting challenges caused by PowerShell.

ADManager Plus can help you meet your compliance audit requirements. Generate a whole set of must-have reports and use them as a key resource when facing compliance audits. You can find a list of Active Directory reports that are relevant to SOX compliance in the SOX Compliance section.

Featured links

Sours: https://www.manageengine.com/products/ad-manager/powershell-scripts-for-ad-user-reports.html
  1. Unit 7 assessment
  2. Maytag refrigerator door replacement
  3. Jerk hut hours
  4. 2008 sprinter camper

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:

Active Directory PowerShell Commands

View all Active Directory commands

get-command -Module ActiveDirectory

Display Basic Domain Information


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


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}

AD User PowerShell 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 }

AD Group Commands

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

AD Computer Commands

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

Group Policy Section

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

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 "[email protected]"

Windows Server & Client Commands

Get all Services


Get all Processes


Display Network Adapters

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


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


Set Execution Policy to Unrestricted

set-executionpolicy unrestricted

Show PowerShell Version


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


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.


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

Related: 15 Windows commands that are still Awesome

Sours: https://activedirectorypro.com/powershell-commands/
6. Create and Manage AD User Account using Powershell

11 PowerShell commands to use in managing Active Directory


Microsoft's PowerShell (PS) management framework developed for systems management and automating administrative tasks extends far beyond simply replacing the venerable command line shell. No, PS offers much more by integrating with services and applications to provide holistic management of clients and servers alike.

As the underlying framework is updated, new, more powerful functions will become available. PS is further enhanced by importing modules of support services, such as Active Directory (AD), which allows admins greater control over the devices and user accounts stored in AD, for example. This capability expands to all facets of maintaining the directory services, including controllers and domain services.

Before diving into the cmdlets, there are a few requirements that must be met to ensure that AD cmdlets are available and fully supported:

  • Administrative PC with Windows Vista installed (or newer)
  • Remote Server Administration Tools installed on administrative PC
  • Server with Windows Server 2008 (or newer)
  • Active Directory Domain Services Role installed on server
  • Windows Management Framework 3.0 (or newer)
  • Switched network (Required for most cmdlets to function properly)
  • Broadband Internet Access (Optional, but recommended)
  • Domain Admin credentials

SEE: Windows administrator's PowerShell script kit (Tech Pro Research)

Accessing Active Directory cmdlets

Start by importing Module Active Directory.

Before being able to run any of the cmdlets that allow for managing AD, the corresponding module must first be imported to the current PS session. Once this has been done, AD cmdlets will now be loaded and within your control.

Note: you must perform this each time PS is run before AD-specific cmdlets will become available.

1. Create computer object

To create a new computer object in a specified organizational unit (OU), enter the cmdlet:

New-ADComputer -Name "ComputerName" -SamAccountName "ComputerName" -Path "OU=Computers,DC=Domain,DC=com"

specifying the object's name for both the -Name and -SamAccountName parameter. Do not forget to include the distinguished name (DN) in quotes after the -Path parameter, which designates where the object is to be created.

This is especially useful when managing multiple sites and/or domains, particularly when scripting changes to AD such as with new account creations, which may be linked to new hires when on-boarded by human resources.

2. Create new security groups

Enter the cmdlet:

New-ADGroup -Name "Security Group Name" -SamAccountName "SecurityGroupName" -GroupCategory Security -GroupScope Global -DisplayName "Security Group Name" -Path "CN=Groups,DC=Domain,DC=com" -Description "Brief description of the what security group is used for"

This cmdlet aids in the creation of such groups, which ease administrative overhead considerably. Managing accounts, and computers is made much easier when applying role-based management settings to security groups versus making changes to each and every account and object singularly.

3. Create a new user account

Enter the cmdlet:

New-ADUser -Name "User Account Name" -SamAccountName "UserAccountName" -AccountPassword (ConvertTo-SecureString "password" -AsPlainText -Force) -DisplayName "User Name" -Enabled $True -GivenName "FirstName" -Path "CN=Users,,DC=Domain,DC=com" -Server "controller.domain.com" -Surname "LastName" -UserPrincipalName "[email protected]"

Creating and managing user accounts go hand-in-hand when AD serves as the backend to an organization's centralized infrastructure. Generating new user accounts can grow to be a tedious task, given all the numerous parameters and text fields present. And while not all are required, many are certainly useful when populated, such as email and title to name a few.

A whole host of these attributes can be configured by adding the -OtherAttributes parameter and pairing it with the attributes you wish to configure, such as the former: @{title="job_title";mail="[email protected]"}, for example.

4. Create a new OU

Enter the cmdlet:

New-ADOrganizationalUnit -Name "OU Name" -Path "DC=Domain,DC=com"

OUs are essential to managing user accounts and computer objects on the back-end of the network. Put another way, a properly set up Active Directory will include a well-designed set of OUs with, which to compartmentalize all the objects that AD centrally manages, making for an orderly, structured directory and one that will seamlessly lend itself to hardening the network while keeping it easy to manage.

Note: Cmdlets beginning with "New" connotate the creation of that object. When the task requires removal of an object, use the "Remove" prefix in place of "New." Additionally, this works when you need to modify an object, instead using the "Set" prefix in place of "New." The syntax for these cmdlets follow a similar format to that of the New-prefixed cmdlets listed above.

5. Add/remove users or computer objects to/from groups

Enter the cmdlet:

Add-ADGroupMember SecurityGroupName -Members Username01 -Server "controller.domain.com" Remove-ADGroupMember SecurityGroupName -Members Username01 -Server "controller.domain.com"

Once user accounts and computer objects are created, admins can choose to add them to existing security groups for added ease of management. By executing this cmdlet, the -Members parameter listing the accounts to be added will gain membership to the security group. When adding multiple accounts, these may be separated by a comma on a single line. Additionally, the -Server parameter though optional, will specify which domain controller to connect to for processing the changes. To remove members from a group, use the Remove-ADGroupMember cmdlet which follows a similar syntax.

6. Obtain the locally stored password from a computer object

Enter the cmdlet:

Get-AdmPwdPassword -ComputerName "computer.domain.net"

For organizations that have implemented Microsoft's excellent (and free) Local Administrator Password Solution (LAPS), there is a cmdlet that can grab the password stored in the computer object within AD and display it in one easy-to-retrieve step versus scouring the database for each object to track down the ms-mcs-AdmPwd attribute.

7. Joining a computer to a domain

Enter the cmdlet:

Add-Computer -DomainName "domain.com" -Credential Domain\Username -Restart -Force

Joining a computer to the domain is one of the most common tasks IT pros perform, tens of thousands of times in their career lifetime. And while the task only takes a few minutes per machine, it can be run from PS to streamline and with a few tweaks, the entire process may even be fully automated. Just remember that the cmdlet--as detailed above --will prompt the admin for their password to complete the domain join before rebooting the device.

8. Enable/Disable users, computers, or service accounts

Enter the cmdlet:

Enable-ADAccount -Identity "ComputerName" Disable-ADAccount -Identity "Username"

It is fairly obvious what this cmdlet does. It enables (or disables) a user account, computer object, or service account managed by AD to allow (or prevent) the user or computer account from being authenticated with or to on the network.

9. Unlock user accounts

Enter the cmdlet:

Unlock-ADAccount -Identity "Username"

It is often noted by statistical analysis that IT spends in ordinate amount of time resolving help desk calls relating to unlocking user's accounts and resetting their passwords. The latter is covered above with the Set-ADUser cmdlet, however, the former is this specific cmdlet. This basically applies to accounts in which users have exceeded their password retry counters and have effectively locked their account from being used. Once unlocked, AD functionality (including authenticating the account) is made available again.

10. Locate disabled computer or user accounts

Enter the cmdlet:

Search-ADAccount -AccountDisabled | FT Name,ObjectClass

The Search-ADAccount cmdlet can be used for more than just finding disabled accounts. There are many parameters that may be invoked to effectively search AD and report back matching results. However, to highlight its functionality, I decided to go with the disabled accounts since it is an important and useful cmdlet to know.

To limit searches to a particular OU, the -SearchBase parameter followed by the DN of the path will be necessary. Additionally, to focus these results on a particular controller, the -Server attribute followed by the Fully Qualified Domain Name (FQDN) should be appended as well.

11. Repair a broken trust between a client and the domain

Enter the cmdlet:

Test-ComputerSecureChannel -Server "controller.domain.com"

A broken channel, as PS refers to it, occurs when the client computer has a broken trust relationship between the domain. It will cease to authenticate domain logins since the client and domain no longer have the channel setup, acting as a link between the two. The cmdlet above tests this relationship against the domain controller to verify that the link still exists. If not, adding the -Repair parameter resets this link between the two, reestablishing the channel.

This is by no means intended to be an exhaustive list of all the cmdlets available to systems or domain administrator's, but rather a listing of cmdlets that are commonly used daily to manage accounts, modify objects, and get relevant information used to resolve issues that impact productivity.

Microsoft Weekly Newsletter

Be your company's Microsoft insider by reading these Windows and Office tips, tricks, and cheat sheets. Delivered Mondays and Wednesdays

Sign up today

Also see

Sours: https://www.techrepublic.com/article/11-powershell-commands-to-use-in-managing-active-directory/

Script powershell ad

How To Get Started with PowerShell and Active Directory Scripting

Build a Full PowerShell Utility

This article is a text version of a lesson from our PowerShell and Active Directory Essentials video course (use code ‘blog’ for free access).

The course has proven to be really popular as it walks you through creating a full Active Directory management utility from first principles.

Get the Free PowerShell and Active Directory Essentials Video Course

I'd recommend this for both new and advanced PowerShell users. Building an AD tool is a great learning experience.

Coding With PowerShell

It can be hard to get started with PowerShell, especially if over the years you’ve become accustomed to working with the cmd.exe command line or batch files. In this article (based on Lesson 2 of our PowerShell and Active Directory course), we’ll cover how and why you should upgrade your skills to PowerShell and the fundamentals of launching the PowerShell editor, command completion and how to get always up to date help and examples.

Running Commands

The PowerShell console is an interactive console that enables you to run various commands in real time. There’s no need to edit a script in Notepad and then run it separately, a big time saver.

If you’re in any organization that’s been around for any length of time, you’ve probably already got some smaller scripts, bat files, or procedures that you run from the cmd.exe command line. Great news! You can invoke all of that from with PowerShell, this was a deep design decision on the part of Microsoft as they were trying to make the transition as easy as possible for sysadmins.

In appearance, the PowerShell editor looks and functions just like the cmd.exe command prompt environment. The utilities and skills you already know will work within PowerShell right now with no modification. If you’re working on making the transition from one-off tasks to enabling a more automated network, getting in the habit of firing up PowerShell instead of the command prompt is a good way to start.

All of your often used utilities like ping, ipconfig, dir, etc will all work exactly as you’ve come to expect.

How to Find PowerShell Commands

People love PowerShell because it’s so, well, powerful. But that power comes from an absolutely insane amount of complexity. It’s just not feasible or practical for someone to memorize all of the different commands, cmdlets, flags, filters and other ways of telling PowerShell what to do.

Thankfully, built right into the editor are multiple tools to help you deal with this fact.

Tab Completion

There’s no need to memorize all of the different commands or exact spelling of a command. Type

Into the editor and hit the TAB key – you’ll cycle through all the commands beginning with what you had input so far. This works at any section of the command you’re trying to invoke, the name (as shown below), but also flags and paths that you’re manipulating to get your desired outcome.


While tab completion works well, what happens if you don’t know the name of the command you’re looking for? In that case, you’d use a command for finding other commands: Get-Command.

In searching for commands, it’s important to keep in mind that there’s a syntax to them: VERB-NOUN. Typically the verbs are things like Get, Set, Add, Clear, Write and Read and the Nouns are the files, servers, or other items within your network and applications.

Get-Command is a discovery tool for exploring the commands available on your system.

PowerShell’s Command Syntax

Someone once described the Perl scripting language as looking like “executable line noise” – an incredibly useful tool with a wildly opaque syntax and a correspondingly high learning curve.

While not quite to that level the traditional command prompt in Windows isn’t too far off. Consider a common task like finding all the items in a directory whose names start with the string ‘Foo’.

FOR and DO indicate that it’s a loop.
The /D flag indicates this is for Directories
The /r flag indicates that “Files Rooted at Path”
The pattern that defines the set of files to be looped over is designated with “in”
@Echo instructs the script to write out the result of each loop and finally
%G is the “implicit parameter” and is chosen because earlier developers had already used the pathname format letters a, d, f, n, p, s, t, and x. So, starting with G is traditional as it gives you the largest set of unused letters for returned variables ( G, H, I, J, K, L, M) – in other words, it’s an ugly hack.

Compare that to the PowerShell equivalent:

The output’s functionally the same, but even in this fairly trivial example, it’s much much easier to understand what’s happening. It’s immediately obvious what all the elements in the command do and how you could modify them. The only slightly non-obvious thing here is the * wildcard character (present in both examples) which indicates that the pattern used to match items should start with ‘Foo’ and end in anything else.

It just keeps getting better from here as say you want to know how to identify just files (not directories) in the path? You could dig up the docs, Google around and try to sort that out with the command line version, or if you’re in PowerShell, type “-” and hit the tab key, rolling through the flag options until the obvious solution shows up.

One Big String vs Object Properties

Servers are no good to anyone if they’re not online. Which is why people spend an inordinate amount of time pretending they’re sonar operators on a submarine and ping’ing them (yes, that’s actually why it’s named that – https://en.wikipedia.org/wiki/Ping_(networking_utility)

While the output from ping is useful (and you can use ping within PowerShell), at the end of the day the output is just a big string – a series of letter and number characters with no defined breaks between them).

PowerShell has a command that’s analogous to ping, but that returns data that’s structured, making it easy to work with. That command is Test-Connection.

Below you can see the output of pinging a server (named ‘DC’ on their local network) and the equivalent Test-Connection output.

Putting aside that it’s easier to read, what’s really important is that you can now pass this information off to another command, incorporate it into a larger utility (as this full course is working towards) or just tweak it so that it makes more sense.

Geting Help System

Up to now, we’ve focused on how to manipulate a particular command as you’re in the middle of it (via tab completion), but as you start doing more and more with PowerShell, the commands become more complex with even more complex options. While the Verb-Noun syntax helps, what helps, even more, is having:

1. Up to date documentation
2. Lots of examples

CmdLet Help

In practice, you should combine Get-Command (to find what to use) and then use Get-Help

A practical example of how to do this: suppose you need to identify all the running Windows Services on a machine.

You would start by looking for commands for service interaction:

Which would tell you at a glance that you were on the right track. Thinking back to the standard Verb-Noun syntax of PowerShell commands, you want to investigate how to properly use ‘Get-Service’.

MicroSoft’s Office Get-Service Documentation

For this, you’d use a new command ‘Get-Help’. Start by typing

“Get-Help -” and hit the Tab key

You’ll quickly find the available options, the most obviously suitable one being “-Name”, so you’d try:

Immediately you get the full Syntax (and that you can include or exclude names based on filters).

If you wanted to deep dive into a particular aspect of the command you can drill down further with Get-Help, including each parameter

PowerShell Help Examples

Because we’re all humans reading this (no offense Google bot), we have the same mental hurdles to overcome with respect to pattern recognition and translating abstract command syntaxes into what we should actually type to accomplish what we need to get through the day.

By entering in “-examples” or included with the “-detail” flag for Get-Help, you’ll be presented with a set of examples for using the command.

Here is the output for:

Staying Up To Date

Nothing is more frustrating than entering in exactly what an example says you should, only to have it not work as documented. Often this is caused by out of date documentation, bad examples, or updated libraries.

Sidestep these frustrations as well as get new examples and fixes with the

Command. you’ll start the download process.

Next Steps with PowerShell

Want to learn more? Use unlock code ‘blog’ for free access to the full PowerShell and Active Directory Essentials video course.

Michael Buckbee

Michael Buckbee

Michael has worked as a syadmin and software developer for Silicon Valley startups to the US Navy and everything in between.

Sours: https://www.varonis.com/blog/how-to-get-started-with-powershell-and-active-directory-scripting/
03 - Powershell for Active Directory - Quering AD Data

Adam the Automator

9 July 2019Active DirectoryPowerShell

Active Directory Scripts Galore: Come and Get It!


Active Directory is one of the most common uses for PowerShell. I have personally been building Active Directory scripts using VBScript and PowerShell for over a decade. Here’s a big sample of Active Directory PowerShell scripts to do all kinds of stuff!

Discover, report and prevent insecure Active Directory account passwords in your environment with Specops’ completely free Password Auditor Pro. Download it today!

All of the Active Directory scripts I’ll be listing here are in various stages of functionality. The point of this post isn’t to give you 100% tested, pristine scripts but rather give you a jumpstart on creating some of your own.

All of the scripts listed here are Active Directory PowerShell scripts. You can script things in Active Directory but if you’ve noticed, PowerShell is sorta my thing. Enjoy!

Active Directory SPNs

User Accounts

  • Bulk-AD-User-Creation.ps1
    Here’s an example of how to create Active Directory users in bulk by reading from a text file.
  • Copy-AD-User-Account.ps1
    Do you use template user accounts that you need to build other accounts from? Look no further! This script copies attributes from a user account and also all group memberships to create a new AD user.
  • FindUnusedUserAccounts.ps1
    Use this script to find Active Directory user accounts that aren’t used anymore and remove them. This script also create a CSV log file.
  • Get-ActiveDirectoryUserActivity.ps1
    This script finds all logon and logoff times of all users on all computers in an Active Directory organizational unit. The appropriate audit policies must be enabled first because the appropriate event IDs will show up.
  • Get-AdUserMatches.ps1
    You’ve got a CSV file full of employee names and need to find their AD user accounts, however, nothing ever matches up 100%. Use this script to find AD user accounts from a CSV file and also get an example of using “fuzzy” searching.
  • Get-All-Docs-Password-Age.ps1
    Here’s a great example of how to pull the user account password age from lots of AD users at once.
  • Get-Inactive-Ad-Users.ps1
    Another example of how to pull employee information from a CSV and find their AD user accounts. This script was used to find inactive accounts.
  • Get-LoggedOnUser.ps1
    Although not technically AD-related, the function in this script queries CIM on the local or a remote computer and returns the user (local or Active Directory) that is currently logged on.
  • GetAdUsersWithPasswordLastSetOlderThan.ps1
    Here’s another older script I built to find AD users that set their password a certain time ago.
  • GetPasswordResetCountXDaysOld.ps1
    Use the code in this script to find all AD users that have set their password. There’s some overlap between this one and GetAdUserWithPasswordLastSetOlderThan.ps1.
  • JEA-PSWA-ActiveDirectory-User-Admin.ps1
    I remember this one! This was a script that took forever that allows you to delegate AD change responsibilities to other users. This was used to delegate HR access to create and change AD users.
  • New-AdUserProvision.ps1
    This an example of a script that covers all the bases. This script does everything from create the user account, assign groups, add to the appropriate OU and even creates a home folder!
  • Get-UserLogonSessionHistory.ps1
    This script finds all logon, logoff and total active session times of all users on all computers specified. For this script to function as expected, the advanced AD policies; Audit Logon, Audit Logoff and Audit Other Logon/Logoff Events must be enabled and targeted to the appropriate computers via GPO.

Active Directory Groups

  • Get-AdGroupMembershipChange.ps1
    This script queries multiple Active Directory groups for new members in a domain. It records group membership in a CSV file in the same location as the script is located. On the script’s initial run it will simply record all members of all groups into this CSV file. On subsequent runs it will query each group’s member list and compare that list to what’s in the CSV file. If any differences are found (added or removed) the script will update the CSV file to reflect current memberships and notify an administrator of which members were either added or removed.
  • Get-EmptyGroup.ps1
    This function queries the Active Directory domain the initiating computer is in for all groups that have no members. This is common when attempting to find groups that can be removed. This does not include default AD groups like Domain Computers, Domain Users, etc.
  • New-AdGroupMembershipMonitor.ps1
    I liked writing this script because it was a foray into security. This script actively monitors an Active Directory group for any membership changes. If any members are added or removed, it can notify you.


  • CompareIEGPO.ps1
    This is an old script but still useful I used to compare two GPOs. This script pulls registry information the GPOs set and compares them to see what the differences are.
  • Get-DisabledGpo.ps1
    This function queries the Active Directory domain the initiating computer is in for all GPOs that either have their computer, user or both settings disabled. This is common when attempting to find GPOs that can be removed.
  • Get-GPO-Reg-Settings.ps1
    Using and some magic, this scripts pulls all of the registry settings one or more GPOs set when applied.
  • Get-GPOs-Linked-To-Empty-OUs.ps1
    This is another good example of a script you can use when cleaning up AD. This one was used to find GPOs that weren’t doing anything at all because they were linked to empty OUs.
  • Get-Gpo-Setting.ps1
    An OK example of finding GPO registry settings.
  • Get-Inactive-GPO-Settings.ps1
    This script finds all GPOs in the current domain which have either the user or computer configuration section enabled yet have no settings enabled in that section. Good script for AD cleanup work.
  • Get-Inactive-GPOs.ps1
    Another example of how to pull GPOs that are not being used anymore.
  • Get-UnlinkedGpo.ps1
    This function queries the Active Directory domain the initiating computer is in for all GPOs that do not have a link to an object. This is common when attempting to find GPOs that can be removed.


  • Get-AdDnsRecordAcl.ps1
    This script retrieves the ACL from an Active Directory-integrated DNS record. This is a good script to use when troubleshooting issues with dynamic DNS.

Active Directory Troubleshooting

  • Get-DcDiag.ps1
    I love the old school dcdiag utility but it wasn’t properly PowerShellified. This is a script that parses dcdiag’s output and returns rich objects.
  • TestSiteReplicationMod.ps1
    Use this script to test to ensure DCs are replicating. It makes a change on one DC and then polls all the other ones to see how long (if at all) that objects takes to replicate.

Organizational Units

  • Get-Empty-OUs.ps1
    Another cleanup script to find all organizational units that are empty. Might as well clean those up!

Computer Accounts

  • Get-Old-Computer-Accounts.ps1
    Need to cleanup old Active Directory computer accounts? Not problem. Take a look at some good examples of using text files and AD to make it happen.
  • Get-ClientsUnderNoSite.ps1
    Sometimes AD clients find themselves not assigned to a site. This can lead to all kinds of problems. Use this script to find those AD computers that are no longer assigned to a site and are calling for help.
  • Rejoin-Computer.ps1
    This script disjoins a computer from an Active Directory domain, performs a reboot and upon coming back up joins it to the domain again and performs another reboot.


That’s it! Those are a few of the Active Directory scripts I’ve built over the years. I sure wish I had been better at keeping track of all of them! I hope these scripts give you a jumpstart on creating some useful Active Directory scripts of your own.

More from Adam The Automator & Friends


Sours: https://adamtheautomator.com/active-directory-scripts/

You will also be interested:

Active Directory is a service that is used by many IT departments and organizations. It can be difficult to manage without the right scripts, especially if you are not an advanced user of PowerShell. This article will introduce best practices for managing Active Directory through PowerShell scripting.

We will start with definitions and explanations of what active directory is, who uses it, and how it can help us accomplish common tasks or maintenance that would otherwise take hours or days to complete manually. We will also talk about some of the best ways to use PowerShell to get things done faster – even if you’re not an expert on this powerful tool!

Active Directory is a powerful service that can be used by IT departments to manage user accounts, permissions and more. Managing Active Directory through the native tools can be difficult if you don’t know how to use PowerShell.

There are various communities that have developed some great scripts for managing AD with PowerShell, but finding them all in one place isn’t easy. We’ve compiled this list of best practices for managing your directory with PowerShell so you don’t have to go searching for each script individually.

This guide will walk you through the most common tasks when working with Active Directory using PowerShell scripts from the community.

Disclaimer: We will not be help responsible for any scripts or commands that you try from this article. Everything here is provided ‘as is’ and has not been tested in a live environment. Use entirely at your own risk.

Common PowerShell Scripts for Managing Active Directory

Using a graphical interface is fine for occasional AD use, but for scaling up your work you really need to start automating. In Windows environments, PowerShell is the king of all scripting languages because it has been developed especially for administrative tasks.

It is available for every modern Windows operating system, and because it uses the same scripting language, scripts can be easily transferred between them without too much hassle.

PowerShell is more than just an admin tool though, and it can be argued (successfully) that it is in fact a programming language in its own right. You can use it to build applications, scripts and services to perform just about anything you can think of, and we love it! Here is an excellent book to get you started if you are new to PowerShell! If you use our link, we get a small affiliate commission at no extra cost to you.

We have compiled a list of common PowerShell commands that will help you to manage Active Directory with ease:

1. Export all users in Active Directory to a CSV file

2. List the computers that have not logged into the domain for more than 30 days

3. Find out which user accounts are disabled and by whom

4. Create a new user account with various attributes

5. Check how many mailboxes exist on Exchange Server 2003 and 2007 

6. Find out who has permissions to create an organizational unit in Active Directory Domain Services

7. Create a new AD user 

8. Delete an AD user 

9. Change the password for an existing user

10. Add or remove a group from a user’s membership list 

11. Enable or disable an Active Directory account

12. Set the expiration date for an Active Directory account to be deleted after it is inactive 

Useful PowerShell Resources

We have put together a list of some of the most responsive and helpful PowerShell communities available to help you with your scripting needs.

Reddit » PowerShell


PowerShell.org Forums


IIS Forum » PowerShell


Spiceworks » PowerShell


Ironman Software Forums » PowerShell Tools



We hope that you have found this information about some of the best active directory scripts on the internet helpful. If you have any questions, please feel free to post them to us on Twitter @itblogpros and we will get back to you as soon as possible. We hope that this article was informative for you!

Sours: https://itblogpros.com/best-powershell-scripts-for-active-directory/

1041 1042 1043 1044 1045