Powershell

Table of Contents

3.1 Active Directory


Installing Active Directory - Module


Active Directory (AD) is by far the most successful in terms of usage directory system across many business worldwide. AD is the backbone for a Windows Domain workspace and is a Windows Server role installed on a Server thus promoting the server to a logical domain controller (DC). The purpose of a Windows Server with Active Directory role installed on it , thus named a Domain Controller, is to provide users access to system resources in a trusted methodology that integrates with countless systems/software and resources all over the technology world.

Objects in the terms of Users, Computers and Groups are created in Active Directory in Organizational Units (OU) which are a file directory hierarchy much like in Windows Explorer. Objects then inherit permissions from the root of the OU. AD Integrates with Group Policy (GP) which is also another Windows role/service within Windows Server that allows creating specific policies to apply to objects within an OU.

A Domain is the name of the network which has an Active Directory Domain Controller active on it. AD can be used to provisions out login details of user objects and different Operating System computers may join the Windows domain. Users may then use their objects login credentials to log into a device joined to the domain to access the domains resources, whether it be for printing, storing files, or browsing an internal Intranet.

Within AD & Group Policy an administrator (admin) may create policies for the most basic Windows Interface such as setting desktop backgrounds to be a custom image, to preventing users from installing software, to sharing shared drives and printers to a user all the way to integrating complex mail servers and DHCP/DNS servers to create a complex Windows network.



Prerequisites

Microsoft have developed a Active Directory module that can be imported into PowerShell to allow system administrators to interact with an Active Directory Domain Controller. Before the AD Module can be imported into PowerShell the PowerShel service will need to be installed on the local device joined to a Windows Server Domain, and the target domain will need to also have PowerShell installed on it, and on a listening state.


Installing AD Module on Windows 7 / 8 / 8.1 / 10 v.1803 and under

Installing PowerShell Module on Windows versions 7/8/8.1 and 10 is as simple as downloading and installing Remote Server Administration Tools (RSAT).

When installing RSAT for your windows OS, make sure your latest update build e.g. Windows Build Version 1607, 1703, 1709... matches the same version build as the RSAT download executable. It's recommended to install the latest Windows Stable Build Version for security reasons by installing the latest Windows updates.

You can find which Windows Build Version you have installed by clicking state (Windows Logo) - Type Run - Click Run - Type 'winver' - then hit enter - The Windows Build number should appear like below.



The installation steps to installing RSAT are below.

1) Download Remote Server Administration Tools (RSAT) for your Windows OS;

For Windows 7 - https://www.microsoft.com/en-au/download/details.aspx?id=7887
For Windows 10 - https://www.microsoft.com/en-au/download/details.aspx?id=45520

2) Add or Remove features

There are 2 (two) ways to add and remove features in Windows 10, either manually through the GUI or through PowerShell, both methods are outlined below.


Manually - Add or remove features

1) Open File explorer
2) Click "This PC"
3) Click Computer (In the top ribbon bar)
4) Click Uninstall or change a program
5) Click Programs and Features (Scroll to bottom of page under Related settings)
6) Click Turn Windows features on or off
Optional - To add the RSAT PowerShell module on the local computer
7) Click the check box next to "Active Directory Lightweight Directory Services"
8) Click OK


PowerShell - Add or remove Windows features

Now the PowerShell module (Or any other feature selected) will be installed on the local machine with the appropriate PowerShell modules able to be imported/loaded into PowerShell.

Run these commands below after installing RSAT on a Windows machine in PowerShell to install the PowerShell module

To Find all Windows features

Get-WindowsOptionalFeature -FeatureName "*" -Online


To find Windows features with specific keywords/characters

Get-WindowsOptionalFeature -Online -FeatureName '*DirectoryServices-ADAM-Client*'


To find list of disabled Windows features only

Get-WindowsOptionalFeature -Online | Where-Object -Property state -eq 'disabled'


Read further on the Get-WindowsOptionalFeature command here


To enable windows features

Enable-WindowsOptionalFeature -Online -FeatureName " DirectoryServices-ADAM-Client"


To enable Windows RSAT PowerShell feature and all dependencies

Enable-WindowsOptionalFeature -Online -FeatureName 'DirectoryServices-ADAM-Client' -all


Read further on the Enable-WindowsOptionalFeature command here


3) Run command in PowerShell to test Module is loaded

import-module activedirectory


Then your PowerShell module will be loaded within your Windows runtime engine and commands may be run straight away.



Installing PS on Windows 10 v.1809 and higher

To find all available RSAT dependencies that are not installed run the below PowerShell line-height
Get-WindowsCapability -Online | Where-Object {$_.Name -like "Rsat*" -AND $_.State -eq "NotPresent"}


To install any RSAT module from above script then run the below line replacing the variable $RSATdependencies with all the above dependencies

Add-WindowsCapability -Online -Name $RSATdependencies


To Install all dependencies at once run the following.

$Install = Get-WindowsCapability -Online | Where-Object {$_.Name -like "Rsat*" -AND $_.State -eq "NotPresent"}
if ($Install -ne $null) {
foreach ($Item in $Install) {
$RsatItem = $Item.Name
Write-Verbose -Verbose "Adding $RsatItem to Windows"
try {
Add-WindowsCapability -Online -Name $RsatItem
}
catch [System.Exception]
{
Write-Verbose -Verbose "Failed to add $RsatItem to Windows"
Write-Warning -Message $_.Exception.Message
}
}
}
else {
Write-Verbose -Verbose "All RSAT features seems to be installed already"
}




Windows Server 2012/2012 R2/2016

Within a Windows Server 2012/2012 R2 or 2016 a PowerShell Window can be opened up and this command run to install the PowerShell module by installing the associated role.

Install-WindowsFeature RSAT-AD-PowerShell


The manual way of installing the PS Module on Windows Server 2008 is below.

1) Start Server Manager.

2) Click Manage - Add Roles and Features.

3) Continue clicking next until you reach Features option.

4) Click the checkbox to Enable Active Directory module for Windows PowerShell by going to Remote Server Administration Tools - Role Administration Tools - Click AD DS and AD LDS Tools.

5) Run command in PowerShell to test Module is loaded

import-module activedirectory




Domain Contollers



When using the Active Directory commandlets, you may come across an instance where access will be denied to do basic commands. Basic troubleshooting in Active Directory revolves around being on an Domain controller within a forrest that a domain admin has access to modify. To check a domain controller you may use command

> Get-ADDomainController -Filter {isreadonly -eq $false} | select name


The above command will filter through all domain controllers that are not set to read only status, from there the user may then add that domain controller as a PS Drive that they can run commands against. e.g.

New-PSDrive -Name Test -PSProvider ActiveDirectory -Root "DC=posh-python,DC=local" -Server AWS-ITS-DC-00:389 -Credential (Get-Credential)
Set-Location Test:




To test if a computer object is joined to an domain

Test-ComputerSecureChannel -Repair -Credential (Get-Credential)



To rejoin domain (If above command ouput is False OR cannot log into domain account on device)

Reset-ComputerMachinePassword –credential (get-credential) -Server (Insert DC name here)




ADFS - Module

$session = new-PSSession -computerName ADFSADC01
Invoke-Command -scriptblock {Import-Module ADSync}
Invoke-Command -scriptblock {Start-ADSyncSyncCycle -PolicyType Delta}
Invoke-Command -computername ADFSADC01 -scriptblock {Get-ADSyncConnectorRunStatus}




AD Objects - Users & Groups


Creating New AD User

New-ADUser -Name 'Nour Yaghi' -GivenName Nour -Surname Yaghi -UserPrincipalName admin@Poshpython.com -Path 'OU=Users,OU=Lidcombe,OU=Sites, OU=Posh Python,DC=com,DC=au'-AccountPassword ($password -asplaintext "P@ssword" | ConvertTo-SecureString -Force) -ChangePasswordAtLogon $True -Enabled $True -OtherAttributes @{mail='admin@Poshpython.com'}




Bulk Import new AD user



$users = Import-Csv -Path ".\New Users.csv"
ForEach ($user in $users)
{
New-ADUser -Name $user.Name -GivenName $user.firstname -Surname $user.surname -UserPrincipalName $user.email -Path"OU=Users,OU=Lidcombe, OU=Sites,OU=Posh Python,DC=com,DC=au" -AccountPassword ($password ="P@ssword" | ConvertTo-SecureString -AsPlainText -Force) -ChangePasswordAtLogon $True -Enabled $True -OtherAttributes@{mail=$user.Email;co='Australia';title=$user.Title}
}




Copy AD User

$Template = Get-AdUser -identity test.user1'
New-AdUser -name 'test user' -givenname 'test' -Surname 'user' -SamAccountName 'test.user' -UserPrincipalName 'test.user@menulog.com' -Title 'test' -description 'test' -Department 'test' -Enabled $True -Instance $Template -AccountPassword (ConvertTo-SecureString "Complete-1" -AsPlainText -force) -Path 'OU=Users,OU=Australia,OU=Australia,OU=Internal,OU=Org,DC=posh-python,DC=local' -PassThru




Unlock Users

Search-ADAccount -LockedOut | Unlock-ADAccount




Reset Active Directory account Password

Set-ADAccountPassword -Identity admin@poshpython.com -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Complete-1" -Force)




Check event log for AD locked out status

Get-winevent -computername dc02 –filterhashtable @{logname='security';id=4740}




Get AD group members, names and emails

Get-ADGroupMember -Identity "groupname" -Recursive | Get-ADUser -Properties Mail | Select-Object Name,Mail | Export-CSV -Path C:\file.csv -NoTypeInformation




Get AD user by email

Get-ADUser -Filter {EmailAddress -like support@poshpython.com}




Get AD Groups that start with character(s)

Get-ADUser -Identity sumeet.singh -Properties memberof | Select-Object -ExpandProperty ` memberof| where {$_ -like "*HA*"}




Find Direct Reports of user

Get-ADUser -Identity jack.chen -Properties directreports | select -ExpandProperty directreports | Get-ADUser | select -Property name, userprincipalname, DistinguishedName




Add 1 or more users/groups to any amount of groups

Add-ADPrincipalGroupMembership -Identity sumeet.singh -MemberOf SGroup1, SGroup2, Distro1, Distro2


Explore Add-ADPrincipalGroupMembership command here


Remove 1 or more users/groups to any amount of groups

Remove-ADPrincipalGroupMembership -Identity sumeet.singh -MemberOf SGroup1, SGroup2, Distro1, Distro2



To copy groups to another existing user use in example below, stevej will be added to johns's groups.

get-aduser -identity johns -properties memberof | select-object memberof -expandproperty memberof | Add-AdGroupMember -Members stevej -ErrorAction Ignore




Get Distribution groups

Get-ADUser -Identity sumeet.singh -Properties memberof | Select-Object -expandProperty memberof | Get-ADGroup -filter {GroupCategory -eq "Distribution"}




Find users email (mail) Alias attribute

Get-ADuser sumeet.singh -Properties ProxyAddresses




Set email (mail) Alias attribute

Set-ADUser -Identity sumeet.singh -Add @{proxyAddresses="smtp:recruitment@poshpython.com"}




Get AD users by Site OU

$adelaide = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Adelaide,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$brisbanne = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Brisbane,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$canberra = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Canberra,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$darwin = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Darwin,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$hobart = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Hobart,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$lidcombe = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Lidcombe,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$melbourne = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Melbourne,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$newcastle = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Newcastle,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name
$perth = Get-ADUser -Filter * -SearchBase “OU=Users,OU=Perth,OU=Sites,OU=Posh Python,DC=com,DC=au” | select name




Find New users that have started within the last 30 days

$When = ((Get-Date).AddDays(-30)).Date
Get-ADUser -Filter {whenCreated -ge $When} -Properties whenCreated | select name




Add Security Group Role to a Security Group

Add-ADPrincipalGroupMembership -Identity HAAUChainsAdvisor -MemberOf RMAUManageOrderAction



Remove AD Object

Remove-ADObject -Identity 'CN=sumeet.singh,CN=users,DC=poshpyhton.com,DC=local'




Remove AD objects by email address

$emails = 'product@poshpython.com','tech@poshpython.com'

ForEach ($email in $emails) {
$email = Get-ADUser -Filter {EmailAddress -like $email}
Remove-ADObject $email.DistinguishedName
}



Remove AD Group member

Remove-ADGroupMember -Identity 'group1' -Members 'alex.johnson'




Find all users in OU with SG starting with

$OU = "ou=users,ou=australia,dc=poshpython.com,dc=local"
$results = @()

get-aduser -searchbase $OU –filter * | % {
$user = $($_.SamAccountName)
$groups = @()
$groups += Get-ADPrincipalGroupMembership -Identity $user | ? { ($_.GroupCategory -eq 'Security') -and (($_.Name -like "HA*") -or ($_.Name -like "RM*")) } | select -ExpandProperty Name
foreach ($group in $groups)
{
$d = '' | select Username, Permission
$d.Username = $user
$d.Permission = $group
$results += $d
}
}
$results | Export-Csv c:\temp\UserMembership.csv -nti





LAPS (Local Administrator Password Solution)


LAPS (Local Administrator Password Solution) is an Active Directory (AD) local administrator password management solution. Local Administrator passwords of AD joined Computer Objects are stored within AD and protected by ACL. This means the local administrator password of a computer can be read through AD to login to the respective computer. LAPS provides a GUI or PowerShell equivalent to access passwords for any domain computer object device to use to login to that computer.

Prerequisities

From Microsoft the general steps to setup LAPS on an AD Domain are below. Full Instructions can be found here
Installation

To setup LAPS (Both the GUI and PowerShell Module) on a local computer first download the executable from here. When installing choose custom installation steps and click to allow all options to be installed locally on the disk.



Once Installed in the Windows Start menu you may search for LAPS UI as a runnable executable, run the following commands in PowerShell to import the module.

Import-Module admpwd.ps
Update-AdmPwdADSchema


Then the shortcut "LAPS UI.exe" executable appears in the Windows Start menu.





Troubleshooting RSAT Installation - Win 10 ver 1903 higher

Disable WSUS

On Domain computers a WSUS or Windows Update Server or alternative may be employed to lock out all unauthorised Microsoft Windows updates to domain joined computers. This is achieved through Group Policy or Agents installed on Windows Devices that prevents the update server from viewing disabled updates, and prevent unauthorised installations of downloaded/cached update files. In these instances RSAT may be blocked on Domain devices and WSUS Group policy setting will need to be disabled.
The following steps provide the complete steps on how to install RSAT on Windows 10 version 1903 and higher OS versions.

Fix error code 0x800f0954

1) On your Windows 10 computer, right click Start and click Run.
Now type gpedit.msc and hit enter.
In the local group policy editor, navigate to Computer Configuration\Administrative Templates\System.
On the right pane look for policy named “Specify settings for optional component installation and component repair.
Right click policy setting and click Enabled. In addition to that, check the box “Download repair content and optional features directly from Windows Updates instead of Windows Server Updates Services (WSUS)“. Click Apply

2) On the local machine start gpedit.msc -> Computer Configuration -> Admin. Templates -> Windows Components -> Windows Update -> Specify intranet Microsoft update service location -> set to Disabled

Fix error code 0x800b0109

3) In gpedit as admin browse to Computer Configuration -> Admin. Templates -> System -> Specify settings for optional component Installation and component repair -> Enable + Check, download repair content and optional features directly from Windows Update instead of Windows Server Update Services (WSUS)

4) Run command in powershell 'gpupdate /force'
5) Restart computer
6) Connect to non domain Wifi
7) Retry to install the RSAT service through Optional Windows features under add or remove programs in Windows. Alternatively run the below script.
$Install = Get-WindowsCapability -Online | Where-Object {$_.Name -like "Rsat*" -AND $_.State -eq "NotPresent"}
if ($Install -ne $null) {
foreach ($Item in $Install) {
$RsatItem = $Item.Name
Write-Verbose -Verbose "Adding $RsatItem to Windows"
try {
Add-WindowsCapability -Online -Name $RsatItem
}
catch [System.Exception]
{
Write-Verbose -Verbose "Failed to add $RsatItem to Windows"
Write-Warning -Message $_.Exception.Message
}
}
}
else {
Write-Verbose -Verbose "All RSAT features seems to be installed already"
}


Visit next page to learn about - 3.2 Exchange