Top Twelve Everyday Powershell Commands

Powershell

PowerShell is a scripting language developed to simplify administrative and IT operation tasks in systems such as Active Directory, Microsoft Exchange and many other Windows-based systems, reducing time and effort.

PowerShell can integrate with services and applications, helping system administrators control and manage users, groups, computers and servers. In addition, Powershell is ever-evolving, becoming more advanced with every new update adding new features.

Let’s take a look at some of the primary and everyday PowerShell cmdlets that can help simplify and automate the management of Active Directory.

 

Note: Before using the Active Directory cmdlets in Powershell, you must import the Active Directory Module into Powershell, also remembering to run Powershell as an Administrator. You do this by running the following command in Windows Powershell:

Import-Module activedirectory

Import-Module

 

1. Using Powershell to create a “New User Account” in Active Directory

Below we can create a new user account using Powershell. When creating user accounts, a few properties are set by default, which are:

  • Accounts created are put into the “Users” container
  • Accounts are created in a disabled state
  • No password is set on the account
  • Users are required to change the password on the first login
  • Accounts become a member of the “Domain Users” group

With that in mind, we will create a usable user account by setting a default password and setting it as enabled; below are the attributes used for making the user account:

  • Name – Tom Smith
  • Given Name – Tom
  • Surname – Smith
  • Sam Account Name – Tsmith
  • Display Name – Tom Smith
  • User Principal Name – Tsmith@company.com
  • Description – Sales Person
  • Path of account location in AD – “OU=Sales, DC=dev, DC=local”
  • Account password = L3tMe1nOK
  • Status – Enabled

Here is the command we will use to perform the account creation:

New-ADUser -Name “Tom Smith” -GivenName “Tom” -Surname “Smith” -SamAccountName “TSmith” -DisplayName “Tom Smith” -UserPrincipalName “TSmith@company.com” -Description “Sales Person” -Path “OU=Sales,DC=dev,DC=local” -AccountPassword (ConvertTo-SecureString “L3tMe1nOK” -AsPlainText -Force) -Enabled $true

Create New User

Note: You can also amend the command to request a password during the creation instead of entering into the command; below is the amended command:

New-ADUser -Name “Tom Smith” -GivenName “Tom” -Surname “Smith” -SamAccountName “TSmith” -DisplayName “Tom Smith” -UserPrincipalName “TSmith@company.com” -Description “Sales Person” -Path “OU=Sales,DC=dev,DC=local” -AccountPassword (Read-Host -AsSecureString “Input Password”) -Enabled $true

 

2. Creating Security Groups with Powershell

In this example, we will create a security group in Active Directory with the following attributes:

  • Name – Sales Team
  • Sam Account Name – SalesTeam
  • Group Category – Security (This can also be set to Distribution)
  • Group Scope – Global (This can also be set to Universal and DomainLocal)
  • Display name – Sales Team
  • Description – Access for Sales Team Data
  • Path of group location in AD – “OU=Groups, DC=dev, DC=local”

Here is the command that we will use to perform the group creation:

New-ADGroup -Name “Sales Team” -SamAccountName “SalesTeam” -GroupCategory Security -GroupScope Global -DisplayName “Sales Team” -Description “Access for Sales Team Data” -Path “OU=Groups,DC=dev,DC=local”

Create Security Group

 

3. Creating a Computer Object using Powershell

This example will show how to create a Computer Object in Active Directory, possibly pre-staging a computer being joined to the domain, with the following attributes:

  • Name – TomsComputer (Normally, the asset details go here)
  • Sam Account Name – TomsComputer
  • Path of computer in AD – “OU= ComputerObjects, DC=dev, DC=local”
  • Description – Toms Laptop (You could put a serial number here)

Here is the command we will use to perform the computer object creation:

New-ADComputer -Name “TomsComputer” -SamAccountName “TomsComputer” -Path “OU=ComputerObjects,DC=dev,DC=local” -Description “Toms Laptop”

Create Computer Object

 

4. Creating new OU with Powershell

This example will show how to create an OU using Powershell with the following attributes:

  • Name – Edinburgh
  • Path of OU in AD – “DC=dev, DC=local”
  • Description – For Edinburgh User Accounts

Here is the command we will use to perform the OU creation:

New-ADOrganizationalUnit -Name “Edinburgh” -Path “DC=dev,DC=local” -Description “For Edinburgh User Accounts”

Create New OU

 

5. Adding/Removing Objects in to or out of Groups

Below is the command to add a user to a group:

Add-ADGroupMember SalesTeam -Members TSmith

Add Member to Group

Note: The command can also be used to add computer objects to groups

Below is the command to remove a user from a group:

Remove-ADGroupMember SalesTeam -Members Tsmith

Remove Member from Group

Once you run the command, you will be asked to confirm if you are sure to perform this action:

Confirm Removal

Note: The command can also be used to remove computer objects from groups

 

6. Getting information of a user account using Powershell

Below is the command to get information about an AD user. The command has many different options to get, filter and save information. The example command shows basic usage, returning all attributes on the user account:

Get-ADUser Tsmith -Properties *

Get-ADuser All Info

If you want to filter on specific attributes, you can use this:

Get-ADUser -Identity Tsmith -Properties * | select DisplayName, GivenName, Surname, Enabled, PasswordNeverExpires

Get-ADUser Specific Info

 

7. Getting information of a computer object using Powershell

Below is the command to get information about a computer object. The command has many different options to return information of the computer object. The example command shows basic usage, returning all attributes on the computer object:

Get-ADComputer -Identity tomscomputer -Properties *

Get-ADComputer all info

If you want to filter on specific attributes, you can use this:

Get-ADComputer -Identity tomscomputer -Properties * | select Name, Operatingsystem, Operatingsystemversion, Description

Get-ADComputer Specific Info

 

8. Getting information of a group using Powershell

Below is the command to get information about a group. The command has many different options to return information of a group. The example command shows basic usage, returning all attributes of the group:

Get-ADGroup -Identity salesteam -Properties *

Get-ADGroup All Info

If you want to filter on specific attributes, you can use this:

Get-ADGroup -Identity salesteam -Properties * | select Name, GroupCategory, GroupScope

Get-ADGroup Specific Info

 

9. Getting information on the members of a group using Powershell

Below is a simple command that allows you to get a list of members of a group:

Get-ADGroupMember -Identity salesteam

Get-ADGroupMember All Info

You can also select to show only specific attributes of the members by using this command:

Get-ADGroupMember -Identity salesteam | select name

Get-ADGroupMember Specific Info

 

10. Setting or applying new attributes on user account with Powershell

The command below will allow you to add extra information to a user account, such as adding a department, company, address or even forcing a user to change password at the next login:

Set-ADUser -Identity tsmith -Department Sales -Company “Mega Sales” -ChangePasswordAtLogon $true

Set-ADUser

 

11. Setting or applying new attributes on a computer object with Powershell

The command below will allow you to make changes or add extra information to a computer object, such as adding an operating system name, version or even a location:

Set-ADComputer -Identity tomscomputer -OperatingSystem “Windows 10 Pro”  -OperatingSystemVersion “10.0 (18363)”

Set-ADComputer

 

12. Setting or applying new attributes on a group with Powershell

The command below will allow you to make changes or add extra information to a group, such as adding a description, changing group scope from a global group to a universal group or adding someone to manage the group:

Set-ADGroup -Identity salesteam -Description “Access for Sales Team Data” -GroupScope Universal -ManagedBy fblog

Set-ADGroup

 

Conclusion

To conclude, these twelve PowerShell commands should help improve your Active Directory environment’s basic management and support. I hope this article has helped you understand how Powershell can help speed up some basic tasks.

Using Azure/O365 Powershell Commands

Azure

Like administering on-premise Active Directory using PowerShell, you can also use PowerShell to manage Azure AD; below are some basic PowerShell commands to manage Azure Active Directory.

First, you need to install the Azure module for PowerShell, which will provide you with Azure cmdlets inside PowerShell; the command to do this is:

Install-Module -Name Az -AllowClobber -Scope CurrentUser

Install AZ Module

Note: if you want to install the command for all users, change -Scope to AllUsers

After install, you can run the following command to see the installed modules:

Get-InstalledModule

List Modules

You will now need to connect to your Azure AD; you can do this by running this command:

Connect-AzureAD

Connect to Azure

You will then be presented with the login screen for Azure AD; use your Azure login details.

Azure Login Screen

To Manage Users

To get basic information on an Azure AD user, use the following command:

Get-AzureADUser -ObjectId user@domain.com

To get detailed information on object use:

Get-AzureADUser -ObjectId user@domain.com | fl

Get User Info

We can use further user attributes to find user account details, such as filtering on Given name starting with:

Get-AzureADUser -Filter “startswith(GivenName,’Zahid’)”

Get filtered User Info

Another useful command is to check for disabled accounts; you can do this by running the following command:

Get-AzureADUser -All $true -Filter ‘accountEnabled eq false’

Get details on disabled accounts

The command can be modified to filter data further by using this command:

Get-AzureADUser -All $true -Filter ‘accountEnabled eq false’ | select DisplayName,UserPrincipalName,Department

Disabled account info filtered

To set a password on a user account in Azure AD

Set-AzureADUserPassword -ObjectId  migrate.dummy4@cloudthing.com -Password (ConvertTo-SecureString -AsPlainText “p@ssw0rd” -Force)

Set Password

This is a similar command to above, setting a password for a user account but forcing the user to change the password at the next login.

Set-AzureADUserPassword -ObjectId  migrate.dummy4@cloudthing.com -Password (ConvertTo-SecureString -AsPlainText “p@ssw0rd” -Force) -ForceChangePasswordNextLogin $true

Change Password Forcing Update

This is the same command as above, but put into a powershell script. It allows user passwords to be set for users from a CSV file, just save the file as a .ps1 file.

# Set the new password

$newPassword = ConvertTo-SecureString -AsPlainText “p@ssw0rd” -Force

# Import users from CSV

Import-Csv “C:\PS_Files\users.csv” | ForEach-Object {

$UserPrincipalName = $_.”UserPrincipalName”

#Un-comment the below line and comment out the above $newpassword line if the CSV will include the password for all users

#$newPassword = ConvertTo-SecureString -AsPlainText $_.”Password” -Force

# Reset user password.

Set-AzureADUserPassword -ObjectID $UserPrincipalName -Password $newPassword -ForceChangePasswordNextLogin $true

Write-Host ” AD Password has been reset for: “$UserPrincipalName

}

Set Password Script

To Manage Mailboxes (Exchange Online)

To Install Exchange Online Module:

Install-Module -Name ExchangeOnlineManagement -Scope AllUsers

To connect to Exchange Onlne:

Connect-ExchangeOnline -EnableErrorReporting -LogDirectoryPath c:/ExchangeLogs -LogLevel All

To get a count of all mailboxes:

(Get-EXOMailbox).count

To get all mailbox results with filtered output:

Get-EXOMailbox | select DisplayName, UserPrincipalName, Alias, RecipientType, RecipientTypeDetails

To get all mailbox results with filtered output:and save to csv file:

Get-EXOMailbox | select DisplayName, UserPrincipalName, Alias, RecipientType, RecipientTypeDetails | Export-Csv C:\PowershellOutput\Exchange\Mailbxoes.csv

Get all mailboxes and pipe it through to retrieve Mailbox statistics and filter on specific details:

Get-EXOMailbox | Get-MailboxStatistics | ft DisplayName, UserPrincipalName, Alias, RecipientType, RecipientTypeDetail

Get all mailboxes and pipe it through to retrieve Mailbox statistics and filter on specific details and save to csv file:

Get-EXOMailbox | Get-EXOMailboxStatistics | select DisplayName, totalitemsize | Export-csv C:\PowershellOutput\Exchange\mailboxSize.csv

This command is used to get details, such as UserPrincipalName, ForwardingSmtpAddress and DeliverToMailboxAndForward.

Get-EXOMailbox Username@Domain.com | select UserPrincipalName,ForwardingSmtpAddress,DeliverToMailboxAndForward

Get Mailbox Info Filtered

To get a full lst of information relating to the mailbox this command can be used:

Get-EXOMailbox username@domain.com | fl

Get All Mailbox Info

To Manage Devices

This command will get a list of all devices in Azure and display only the selected information, such as Display Name, Device Trust Type, Approximate Last Logon time, etc. It will also export this information to a CSV file.

Get-AzureADDevice -All $True | select DisplayName, DeviceTrustType,DeviceOSversion, DeviceOSType, ApproximateLastLogonTimeStamp, @{n=”Owner”;e={(Get-AzureADDeviceRegisteredOwner -ObjectId $_.ObjectId).DisplayName}} | Sort-Object Owner | Export-Csv C:\PowershellOutput\ActiveDirectory\All_Computers.csv

Manage Devices

This command is similar to the one above but adds the information to a variable which many other commands can reference:

$alldevices = Get-AzureADDevice

foreach ($item in $alldevices) {

    Get-AzureADDevice -ObjectId $item.ObjectId | select  DisplayName, DeviceOSType, ProfileType, ApproximateLastLogonTimeStamp

}

OneDrive

This is the command used to install the module to administer OneDrive:

Install-Module -Name Microsoft.Online.SharePoint.PowerShell

Install Module

To connect poswershell to the service to manage OneDrive.

Connect-SPOService -Url https://domainname-admin.sharepoint.com

Connect Service

Provisioning a Business OneDrive, this is useful for when doing a migration

Request-SPOPersonalSite -UserEmails Dummy.Account@domain.com

Provision OneDrive

This is an ever growing document and more will be added over time..