Active Directory
GET
The following is a complete list of all the Get commands for Active Directory in PowerShell v5
(Get-Command -verb get -Module activedirectory).name
PS C:\> (Get-Command -verb get -Module activedirectory).name
Get-ADAccountAuthorizationGroup
Get-ADAccountResultantPasswordReplicationPolicy
Get-ADAuthenticationPolicy
Get-ADAuthenticationPolicySilo
Get-ADCentralAccessPolicy
Get-ADCentralAccessRule
Get-ADClaimTransformPolicy
Get-ADClaimType
Get-ADComputer
Get-ADComputerServiceAccount
Get-ADDCCloningExcludedApplicationList
Get-ADDefaultDomainPasswordPolicy
Get-ADDomain
Get-ADDomainController
Get-ADDomainControllerPasswordReplicationPolicy
Get-ADDomainControllerPasswordReplicationPolicyUsage
Get-ADFineGrainedPasswordPolicy
Get-ADFineGrainedPasswordPolicySubject
Get-ADForest
Get-ADGroup
Get-ADGroupMember
Get-ADObject
Get-ADOptionalFeature
Get-ADOrganizationalUnit
Get-ADPrincipalGroupMembership
Get-ADReplicationAttributeMetadata
Get-ADReplicationConnection
Get-ADReplicationFailure
Get-ADReplicationPartnerMetadata
Get-ADReplicationQueueOperation
Get-ADReplicationSite
Get-ADReplicationSiteLink
Get-ADReplicationSiteLinkBridge
Get-ADReplicationSubnet
Get-ADReplicationUpToDatenessVectorTable
Get-ADResourceProperty
Get-ADResourcePropertyList
Get-ADResourcePropertyValueType
Get-ADRootDSE
Get-ADServiceAccount
Get-ADTrust
Get-ADUser
Get-ADUserResultantPasswordPolicy
I have not used all of these commands so I will concentrate on the ones I have used.
The two commands that I have used the most are Get-ADComputerand Get-ADUser. So I will start there.
Get-ADComputer
If just type Get-ADComputer PowerShell will prompt you for a filter. You can type * if you want all computers but as it is best to filter to the left you should filter based on the information that you are interested in E.G.
Get-ADComputer -Filter {name -like "te*"}
[dc]: PS C:\> Get-ADComputer -Filter {name -like "te*"}
DistinguishedName : CN=test1,CN=Computers,DC=company,DC=pri
DNSHostName :
Enabled : True
Name : test1
ObjectClass : computer
ObjectGUID : 1c824ad7-47af-46ff-8057-61c77a599cd1
SamAccountName : TEST1$
SID : S-1-5-21-1973040400-4026026656-3317648685-1381
UserPrincipalName :
DistinguishedName : CN=test2,CN=Computers,DC=company,DC=pri
DNSHostName :
Enabled : True
Name : test2
ObjectClass : computer
ObjectGUID : f6c054ef-2634-4ff4-92b2-7794dc0a520c
SamAccountName : test2$
SID : S-1-5-21-1973040400-4026026656-3317648685-1382
UserPrincipalName :
If you want to view any property that is not included in the default output you need to include the properties flag. Properties * produces a lot of information
[dc]: PS C:\> Get-ADComputer -Filter {name -eq "test1"} -Properties *
AccountExpirationDate :
accountExpires : 9223372036854775807
AccountLockoutTime :
AccountNotDelegated : False
AllowReversiblePasswordEncryption : False
AuthenticationPolicy : {}
AuthenticationPolicySilo : {}
BadLogonCount : 0
badPasswordTime : 0
badPwdCount : 0
CannotChangePassword : False
CanonicalName : company.pri/Computers/test1
Certificates : {}
CN : test1
codePage : 0
CompoundIdentitySupported : {}
countryCode : 0
Created : 10/06/2020 9:57:13 AM
createTimeStamp : 10/06/2020 9:57:13 AM
Deleted :
Description :
DisplayName :
DistinguishedName : CN=test1,CN=Computers,DC=company,DC=pri
DNSHostName :
DoesNotRequirePreAuth : False
dSCorePropagationData : {1/01/1601 10:00:00 AM}
Enabled : True
HomedirRequired : False
HomePage :
instanceType : 4
IPv4Address :
IPv6Address :
isCriticalSystemObject : False
isDeleted :
KerberosEncryptionType : {}
LastBadPasswordAttempt :
LastKnownParent :
lastLogoff : 0
lastLogon : 0
LastLogonDate :
localPolicyFlags : 0
Location :
LockedOut : False
logonCount : 0
ManagedBy :
MemberOf : {}
MNSLogonAccount : False
Modified : 10/06/2020 9:57:13 AM
modifyTimeStamp : 10/06/2020 9:57:13 AM
msDS-User-Account-Control-Computed : 0
Name : test1
nTSecurityDescriptor : System.DirectoryServices.ActiveDirectorySecurity
ObjectCategory : CN=Computer,CN=Schema,CN=Configuration,DC=company,DC=pri
ObjectClass : computer
ObjectGUID : 1c824ad7-47af-46ff-8057-61c77a599cd1
objectSid : S-1-5-21-1973040400-4026026656-3317648685-1381
OperatingSystem :
OperatingSystemHotfix :
OperatingSystemServicePack :
OperatingSystemVersion :
PasswordExpired : False
PasswordLastSet : 10/06/2020 9:57:13 AM
PasswordNeverExpires : False
PasswordNotRequired : False
PrimaryGroup : CN=Domain Computers,CN=Users,DC=company,DC=pri
primaryGroupID : 515
PrincipalsAllowedToDelegateToAccount : {}
ProtectedFromAccidentalDeletion : False
pwdLastSet : 132362206334921807
SamAccountName : TEST1$
sAMAccountType : 805306369
sDRightsEffective : 15
ServiceAccount : {}
ServicePrincipalNames : {}
SID : S-1-5-21-1973040400-4026026656-3317648685-1381
SIDHistory : {}
TrustedForDelegation : False
TrustedToAuthForDelegation : False
UseDESKeyOnly : False
userAccountControl : 4096
userCertificate : {}
UserPrincipalName :
uSNChanged : 49189
uSNCreated : 49185
whenChanged : 10/06/2020 9:57:13 AM
whenCreated : 10/06/2020 9:57:13 AM
Properties * is good for finding out what all the available properties are but is not recommended for regular use as it puts a load on Active Directory
It is best to limit properties to the things you are interested in. -properties does not accept wildcard characters and it is one of the few plural parameters.
Get-ADComputer -Filter {name -eq "test1"} -Properties PasswordLastSet,PasswordExpired
[dc]: PS C:\> Get-ADComputer -Filter {name -eq "test1"} -Properties PasswordLastSet,PasswordExpired
DistinguishedName : CN=test1,CN=Computers,DC=company,DC=pri
DNSHostName :
Enabled : True
Name : test1
ObjectClass : computer
ObjectGUID : 1c824ad7-47af-46ff-8057-61c77a599cd1
PasswordExpired : False
PasswordLastSet : 10/06/2020 9:57:13 AM
SamAccountName : TEST1$
SID : S-1-5-21-1973040400-4026026656-3317648685-1381
UserPrincipalName :
Get-ADUser
Get-ADUser works very similar to Get-ADComputer except that users have more fields
Get-ADUser -Filter {givenname -eq "Adam"} -ResultSetSize 1 -Properties *
Get-ADUser -Filter {givenname -eq "Adam"} -ResultSetSize 1 -Properties *
AccountExpirationDate :
accountExpires : 9223372036854775807
AccountLockoutTime :
AccountNotDelegated : False
AllowReversiblePasswordEncryption : False
AuthenticationPolicy : {}
AuthenticationPolicySilo : {}
BadLogonCount : 0
badPasswordTime : 0
badPwdCount : 0
c : AU
CannotChangePassword : False
CanonicalName : company.pri/QLD/Adam.Smith31
Certificates : {}
City : Melbourne
CN : Adam.Smith31
codePage : 0
Company : company
CompoundIdentitySupported : {}
Country : AU
countryCode : 0
Created : 9/06/2020 10:44:20 AM
createTimeStamp : 9/06/2020 10:44:20 AM
Deleted :
Department :
Description :
DisplayName : Adam Smith31
DistinguishedName : CN=Adam.Smith31,OU=QLD,DC=company,DC=pri
Division :
DoesNotRequirePreAuth : False
dSCorePropagationData : {1/01/1601 10:00:00 AM}
EmailAddress : Adam.Smith31@lab.pri
EmployeeID :
EmployeeNumber :
Enabled : True
Fax :
GivenName : Adam
HomeDirectory : c:\home\Adam.Smith31
HomedirRequired : False
HomeDrive : H
HomePage :
HomePhone :
Initials :
instanceType : 4
isDeleted :
KerberosEncryptionType : {}
l : Melbourne
LastBadPasswordAttempt :
LastKnownParent :
lastLogoff : 0
lastLogon : 0
LastLogonDate :
LockedOut : False
logonCount : 0
LogonWorkstations :
mail : Adam.Smith31@lab.pri
Manager :
MemberOf : {CN=BrisbaneUsers,OU=QLD,DC=company,DC=pri}
MNSLogonAccount : False
MobilePhone :
Modified : 9/06/2020 10:44:21 AM
modifyTimeStamp : 9/06/2020 10:44:21 AM
msDS-User-Account-Control-Computed : 0
Name : Adam.Smith31
nTSecurityDescriptor : System.DirectoryServices.ActiveDirectorySecurity
ObjectCategory : CN=Person,CN=Schema,CN=Configuration,DC=company,DC=pri
ObjectClass : user
ObjectGUID : 0b7bbdac-41d4-4974-819e-7a473765fb02
objectSid : S-1-5-21-1973040400-4026026656-3317648685-1103
Office :
OfficePhone :
Organization :
OtherName :
PasswordExpired : False
PasswordLastSet : 9/06/2020 10:44:20 AM
PasswordNeverExpires : True
PasswordNotRequired : False
POBox :
PostalCode :
PrimaryGroup : CN=Domain Users,CN=Users,DC=company,DC=pri
primaryGroupID : 513
PrincipalsAllowedToDelegateToAccount : {}
ProfilePath :
ProtectedFromAccidentalDeletion : False
pwdLastSet : 132361370609356846
SamAccountName : Adam.Smith31
sAMAccountType : 805306368
ScriptPath :
sDRightsEffective : 15
ServicePrincipalNames : {}
SID : S-1-5-21-1973040400-4026026656-3317648685-1103
SIDHistory : {}
SmartcardLogonRequired : False
sn : Smith31
st : Victoria
State : Victoria
StreetAddress :
Surname : Smith31
Title :
TrustedForDelegation : False
TrustedToAuthForDelegation : False
UseDESKeyOnly : False
userAccountControl : 66048
userCertificate : {}
UserPrincipalName :
uSNChanged : 45088
uSNCreated : 45084
whenChanged : 9/06/2020 10:44:21 AM
whenCreated : 9/06/2020 10:44:20 AM
Other filtering options
There are a lot of telephone options in Active Directory. This example covers most of them:
Get-ADUser -Filter {samaccountname -eq "Anthony.Walsh3"} -Properties HomePhone,MobilePhone,OfficePhone,otherTelephone,telephoneNumber
Get-ADUser -Filter {samaccountname -eq "Anthony.Walsh3"} -Properties HomePhone,MobilePhone,OfficePhone,otherTelephone,telephoneNumber
DistinguishedName : CN=Anthony.Walsh3,OU=QLD,DC=company,DC=pri
Enabled : True
GivenName : Anthony
HomePhone :
MobilePhone : 041333333
Name : Anthony.Walsh3
ObjectClass : user
ObjectGUID : 4da84d5d-1fb3-4acf-86d3-fd7c16dad711
OfficePhone : 05 5555 5555
otherTelephone : {05 4444 4444}
SamAccountName : Anthony.Walsh3
SID : S-1-5-21-1973040400-4026026656-3317648685-1122
Surname : Walsh3
telephoneNumber : 05 5555 5555
UserPrincipalName : Anthony.Walsh3@company.pri
Another way to filter is to use the option -SearchBase this limits the seach to the OU specified
Get-ADUser -Filter * -SearchBase "OU=QLD,DC=company,DC=pri" -ResultSetSize 3
[dc]: PS C:\> Get-ADUser -Filter * -SearchBase "OU=QLD,DC=company,DC=pri" -ResultSetSize 3
DistinguishedName : CN=Adam.Smith31,OU=QLD,DC=company,DC=pri
Enabled : True
GivenName : Adam
Name : Adam.Smith31
ObjectClass : user
ObjectGUID : 0b7bbdac-41d4-4974-819e-7a473765fb02
SamAccountName : Adam.Smith31
SID : S-1-5-21-1973040400-4026026656-3317648685-1103
Surname : Smith31
UserPrincipalName :
DistinguishedName : CN=adam.odempsey,OU=QLD,DC=company,DC=pri
Enabled : True
GivenName : adam
Name : adam.odempsey
ObjectClass : user
ObjectGUID : c84a6475-7409-4f57-a0e8-a8afd166e2e4
SamAccountName : adam.odempsey
SID : S-1-5-21-1973040400-4026026656-3317648685-1104
Surname : odempsey
UserPrincipalName :
DistinguishedName : CN=Alex.Kenley_sup2,OU=QLD,DC=company,DC=pri
Enabled : True
GivenName : Alex
Name : Alex.Kenley_sup2
ObjectClass : user
ObjectGUID : 2b9f0f8c-c306-43ad-935e-6ada0addc01b
SamAccountName : Alex.Kenley_sup2
SID : S-1-5-21-1973040400-4026026656-3317648685-1105
Surname : Kenley_sup2
UserPrincipalName :
Get-ADObject
Another major get command is Get-ADObject you can use this is you have the name of something in active directory and you want to find out if it is a user a group a computer or whatever it is you can use Get-ADObject
(Get-ADObject -Filter {name -eq 'test1'}).objectclass
computer
Search
Along with Get there is also Search. This is useful for finding Locked out accounts, Disabled accounts, Expires accounts, Inactive accounts, Accounts that are set to have password never expire, And accounts that are about to expire.
It is useful for finding old stale accounts so that you can deal with them according to whatever you policy is.
Search-ADAccount
[dc]: PS C:\> Get-Help Search-ADAccount
NAME
Search-ADAccount
SYNOPSIS
Gets Active Directory user, computer, or service accounts.
SYNTAX
Search-ADAccount []
DESCRIPTION
The Search-ADAccount cmdlet retrieves one or more user, computer, or service accounts that meet the criteria specified by the
parameters. Search criteria include account and password status. For example, you can search for all accounts that have expired
by specifying the AccountExpired parameter. Similarly, you can search for all accounts with an expired password by specifying
the PasswordExpired parameter. You can limit the search to user accounts by specifying the UsersOnly parameter. Similarly, when
you specify the ComputersOnly parameter, the cmdlet only retrieves computer accounts.
Some search parameters, such as AccountExpiring and AccountInactive use a default time that you can change by specifying the
DateTime or TimeSpan parameter. The DateTime parameter specifies a distinct time. The TimeSpan parameter specifies a time range
from the current time. For example, to search for all accounts that expire in 10 days, specify the AccountExpiring and TimeSpan
parameter and set the value of TimeSpan to "10.00:00:00". To search for all accounts that expire before December 31, 2012, set
the DateTime parameter to "12/31/2012".
[dc]: PS C:\> Get-Help Search-ADAccount -Examples
NAME
Search-ADAccount
SYNOPSIS
Gets Active Directory user, computer, or service accounts.
-------------------------- EXAMPLE 1 --------------------------
C:\PS>Search-ADAccount -AccountDisabled | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Guest user
krbtgt user
krbtgt_51399 user
AmyAl-LPTOP computer
DeepakAn-DSKTOP computer
Description
-----------
Returns all users, computers and service accounts that are disabled.
-------------------------- EXAMPLE 2 --------------------------
C:\PS>Search-ADAccount -AccountDisabled -UsersOnly | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Guest user
krbtgt user
krbtgt_51399 user
Description
-----------
Returns all users that are disabled.
-------------------------- EXAMPLE 3 --------------------------
C:\PS>Search-ADAccount -AccountExpired | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Greg Chapman user
Claus Hansen user
Tomasz Bochenek user
Description
-----------
Returns all users, computers and service accounts that are expired.
-------------------------- EXAMPLE 4 --------------------------
C:\PS>Search-ADAccount -AccountExpiring -TimeSpan 6.00:00:00 | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Iulian Calinov user
John Campbell user
Garth Fort user
Description
-----------
Returns all users, computers and service accounts that will expire in the next 6 days.
-------------------------- EXAMPLE 5 --------------------------
C:\PS>Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
FABRIKAM-RODC1 computer
Guest user
krbtgt user
krbtgt_51399 user
Almudena Benito user
Aaron Con user
Adina Hagege user
Aaron Nicholls user
Aaron M. Painter user
Jeff Phillips user
Flemming Pedersen use
Description
-----------
Returns all accounts that have been inactive for the last 90 days.
-------------------------- EXAMPLE 6 --------------------------
C:\PS>Search-ADAccount -PasswordExpired | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Stan Orme user
Danni Ortman user
Matej Potokar user
Description
-----------
Returns all accounts where the password has expired.
-------------------------- EXAMPLE 7 --------------------------
C:\PS>Search-ADAccount -PasswordNeverExpires | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Guest user
Toni Poe user
Anders Riis user
Fabien Hernoux user
Description
-----------
Returns all accounts with a password that will never expire.
-------------------------- EXAMPLE 8 --------------------------
C:\PS>Search-ADAccount -LockedOut | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Toni Poe user
Description
-----------
Returns all accounts that have been locked out.
-------------------------- EXAMPLE 9 --------------------------
C:\PS>Search-ADAccount -AccountDisabled -ComputersOnly | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
TPOE-PC1 computer
Description
-----------
Returns all disabled computer accounts.
-------------------------- EXAMPLE 10 --------------------------
C:\PS>Search-ADAccount -AccountExpiring -DateTime "3/18/2009" | FT Name,ObjectClass -A
Name ObjectClass
---- -----------
Anders Riis user
Description
-----------
Returns all accounts which expire on the 18th of March, 2009.
-------------------------- EXAMPLE 11 --------------------------
C:\PS>Search-AdAccount -AccountDisabled -SearchBase "DC=AppNC" -Server "FABRIKAM-SRV1:60000"
Enabled : False
Name : SanjayPatel
UserPrincipalName :
PasswordNeverExpires :
LockedOut : False
ObjectGUID : d671de28-6e40-42a7-b32c-63d336de296d
ObjectClass : user
SID : S-1-510474493-936115905-2231798853-1260534229-4171027843-767619944
PasswordExpired : False
LastLogonDate :
DistinguishedName : CN=SanjayPatel,OU=AccountDeptOU,DC=AppNC
AccountExpirationDate :
Description
-----------
Returns all users, computers and service accounts that are disabled in the LDS instance: "FABRIKAM-SRV1:60000".
New
The following is a complete list of all the NEW commands for Active Directory in PowerShell v5
(Get-Command -verb new -Module activedirectory).name
New-ADAuthenticationPolicy
New-ADAuthenticationPolicySilo
New-ADCentralAccessPolicy
New-ADCentralAccessRule
New-ADClaimTransformPolicy
New-ADClaimType
New-ADComputer
New-ADDCCloneConfigFile
New-ADFineGrainedPasswordPolicy
New-ADGroup
New-ADObject
New-ADOrganizationalUnit
New-ADReplicationSite
New-ADReplicationSiteLink
New-ADReplicationSiteLinkBridge
New-ADReplicationSubnet
New-ADResourceProperty
New-ADResourcePropertyList
New-ADServiceAccount
New-ADUser
Creating a new user with New-ADUser
There are a lot of options when creating a new user
New-ADUser [-Name] <String> [-AccountExpirationDate <DateTime>] [-AccountNotDelegated <Boolean>] [-AccountPassword
<SecureString>] [-AllowReversiblePasswordEncryption <Boolean>] [-AuthenticationPolicy <ADAuthenticationPolicy>]
[-AuthenticationPolicySilo <ADAuthenticationPolicySilo>] [-AuthType {Negotiate | Basic}] [-CannotChangePassword
<Boolean>] [-Certificates <X509Certificate[]>] [-ChangePasswordAtLogon <Boolean>] [-City <String>] [-Company
<String>] [-CompoundIdentitySupported <Boolean>] [-Country <String>] [-Credential <PSCredential>] [-Department
<String>] [-Description <String>] [-DisplayName <String>] [-Division <String>] [-EmailAddress <String>]
[-EmployeeID <String>] [-EmployeeNumber <String>] [-Enabled <Boolean>] [-Fax <String>] [-GivenName <String>]
[-HomeDirectory <String>] [-HomeDrive <String>] [-HomePage <String>] [-HomePhone <String>] [-Initials <String>]
[-Instance <ADUser>] [-KerberosEncryptionType {None | DES | RC4 | AES128 | AES256}] [-LogonWorkstations <String>]
[-Manager <ADUser>] [-MobilePhone <String>] [-Office <String>] [-OfficePhone <String>] [-Organization <String>]
[-OtherAttributes <Hashtable>] [-OtherName <String>] [-PassThru] [-PasswordNeverExpires <Boolean>]
[-PasswordNotRequired <Boolean>] [-Path <String>] [-POBox <String>] [-PostalCode <String>]
[-PrincipalsAllowedToDelegateToAccount <ADPrincipal[]>] [-ProfilePath <String>] [-SamAccountName <String>]
[-ScriptPath <String>] [-Server <String>] [-ServicePrincipalNames <String[]>] [-SmartcardLogonRequired <Boolean>]
[-State <String>] [-StreetAddress <String>] [-Surname <String>] [-Title <String>] [-TrustedForDelegation
<Boolean>] [-Type <String>] [-UserPrincipalName <String>] [-Confirm] [-WhatIf] [<CommonParameters>]
There are actually more options that can not be set durring account creating and need to be set with Set-ADUser
For a quick example of how to create a user account that can actully log on click the button.
New-ADUser -Name "John.Smith" -SamAccountName "John.Smith" -AccountPassword (ConvertTo-SecureString -AsPlainText "P@ssw0rd99" -Force)`
-Path "OU=NSW,DC=company,DC=pri" -GivenName "John" -Surname "Smith"
New-ADComputer
This command prestages computer accounts
New-ADComputer [-Name] <String> [-AccountExpirationDate <DateTime>] [-AccountNotDelegated <Boolean>]
[-AccountPassword <SecureString>] [-AllowReversiblePasswordEncryption <Boolean>] [-AuthenticationPolicy
<ADAuthenticationPolicy>] [-AuthenticationPolicySilo <ADAuthenticationPolicySilo>] [-AuthType {Negotiate | Basic}]
[-CannotChangePassword <Boolean>] [-Certificates <X509Certificate[]>] [-ChangePasswordAtLogon <Boolean>]
[-CompoundIdentitySupported <Boolean>] [-Credential <PSCredential>] [-Description <String>] [-DisplayName
<String>] [-DNSHostName <String>] [-Enabled <Boolean>] [-HomePage <String>] [-Instance <ADComputer>]
[-KerberosEncryptionType {None | DES | RC4 | AES128 | AES256}] [-Location <String>] [-ManagedBy <ADPrincipal>]
[-OperatingSystem <String>] [-OperatingSystemHotfix <String>] [-OperatingSystemServicePack <String>]
[-OperatingSystemVersion <String>] [-OtherAttributes <Hashtable>] [-PassThru] [-PasswordNeverExpires <Boolean>]
[-PasswordNotRequired <Boolean>] [-Path <String>] [-PrincipalsAllowedToDelegateToAccount <ADPrincipal[]>]
[-SAMAccountName <String>] [-Server <String>] [-ServicePrincipalNames <String[]>] [-TrustedForDelegation
<Boolean>] [-UserPrincipalName <String>] [-Confirm] [-WhatIf] [<CommonParameters>]
Here is an example
New-ADComputer -Name "test04" -SamAccountName "test04" -Path "OU=companyComputers,DC=Company,DC=pri"
New-ADOrganizationalUnit
Creates a new organizational unit or OU if you prefer
New-ADOrganizationalUnit -Name WA -Path "DC=COMPANY,DC=PRI" -ProtectedFromAccidentalDeletion $true
Get-ADOrganizationalUnit -Filter * | select DistinguishedName
DistinguishedName
-----------------
OU=Domain Controllers,DC=company,DC=pri
OU=NSW,DC=company,DC=pri
OU=QLD,DC=company,DC=pri
OU=VIC,DC=company,DC=pri
OU=WA,DC=company,DC=pri
New-ADGroup
Used to create groups in Active Directory
New-ADGroup [-Name] <String> [-GroupScope] {DomainLocal | Global | Universal} [-AuthType {Negotiate | Basic}] [-Credential <PSCredential>]
[-Description <String>] [-DisplayName <String>] [-GroupCategory {Distribution | Security}] [-HomePage <String>]
[-Instance <ADGroup>] [-ManagedBy <ADPrincipal>] [-OtherAttributes <Hashtable>] [-PassThru] [-Path <String>] [-SamAccountName <String>]
[-Server <String>] [-Confirm] [-WhatIf] [<CommonParameters>]
New-ADGroup -Path "OU=WA,DC=company,DC=pri" -Name PerthUsers -GroupScope DomainLocal -GroupCategory Security
Get-ADGroup -SearchBase "OU=WA,DC=company,DC=pri" -Filter *
DistinguishedName : CN=PerthUsers,OU=WA,DC=company,DC=pri
GroupCategory : Security
GroupScope : DomainLocal
Name : PerthUsers
ObjectClass : group
ObjectGUID : 2e806312-dc76-4162-9bf6-38bfcaa6c483
SamAccountName : PerthUsers
SID : S-1-5-21-1973040400-4026026656-3317648685-1389
SET
Set-ADUser
This is used to modify an existing Active Directory User
Set-ADUser [-Identity] <ADUser> [-AccountExpirationDate <DateTime>] [-AccountNotDelegated <Boolean>] [-Add <Hashtable>]
[-AllowReversiblePasswordEncryption <Boolean>] [-AuthenticationPolicy <ADAuthenticationPolicy>] [-AuthenticationPolicySilo
<ADAuthenticationPolicySilo>] [-AuthType {Negotiate | Basic}] [-CannotChangePassword <Boolean>] [-Certificates <Hashtable>]
[-ChangePasswordAtLogon <Boolean>] [-City <String>] [-Clear <String[]>] [-Company <String>] [-CompoundIdentitySupported
<Boolean>] [-Country <String>] [-Credential <PSCredential>] [-Department <String>] [-Description <String>] [-DisplayName <String>]
[-Division <String>] [-EmailAddress <String>] [-EmployeeID <String>] [-EmployeeNumber <String>] [-Enabled <Boolean>]
[-Fax <String>] [-GivenName <String>] [-HomeDirectory <String>] [-HomeDrive <String>] [-HomePage <String>] [-HomePhone <String>]
[-Initials <String>] [-KerberosEncryptionType {None | DES | RC4 | AES128 | AES256}] [-LogonWorkstations <String>] [-Manager
<ADUser>] [-MobilePhone <String>] [-Office <String>] [-OfficePhone <String>] [-Organization <String>] [-OtherName <String>]
[-Partition <String>] [-PassThru] [-PasswordNeverExpires <Boolean>] [-PasswordNotRequired <Boolean>] [-POBox <String>]
[-PostalCode <String>] [-PrincipalsAllowedToDelegateToAccount <ADPrincipal[]>] [-ProfilePath <String>] [-Remove <Hashtable>]
[-Replace <Hashtable>] [-SamAccountName <String>] [-ScriptPath <String>] [-Server <String>] [-ServicePrincipalNames
<Hashtable>] [-SmartcardLogonRequired <Boolean>] [-State <String>] [-StreetAddress <String>] [-Surname <String>]
[-Title <String>] [-TrustedForDelegation <Boolean>] [-UserPrincipalName <String>] [-Confirm] [-WhatIf] [<CommonParameters>]
Set-ADUser [-AuthType {Negotiate | Basic}] [-Credential <PSCredential>] [-PassThru] [-SamAccountName <String>]
[-Server <String>] -Instance <ADUser> [-Confirm] [-WhatIf] [<CommonParameters>]
Changing Extended Attributes
There are three actions you can perform on extended attributes Clear, Replace, and Add
Add adds a value where the the value is not presently set
Set-ADUser -Identity "John.Smith" -Add @{extensionAttribute4="someString"}
Clear removes a value previously set
Set-ADUser -Identity "John.Smith" -clear msExchRemoteRecipientType
Finally replace, replaces a value for another one
Set-ADUser -Identity John.smith -replace @{pager=555555;msExchRecipientDisplayType=555666}
ADD
There is not as many add commands, I will include the one I have used most which is Add-ADGroupMember
[dc]: PS C:\> Get-Command -Verb add -Module ActiveDirectory
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Add-ADCentralAccessPolicyMember 1.0.1.0 ActiveDirectory
Cmdlet Add-ADComputerServiceAccount 1.0.1.0 ActiveDirectory
Cmdlet Add-ADDomainControllerPasswordReplicationPolicy 1.0.1.0 ActiveDirectory
Cmdlet Add-ADFineGrainedPasswordPolicySubject 1.0.1.0 ActiveDirectory
Cmdlet Add-ADGroupMember 1.0.1.0 ActiveDirectory
Cmdlet Add-ADPrincipalGroupMembership 1.0.1.0 ActiveDirectory
Cmdlet Add-ADResourcePropertyListMember 1.0.1.0 ActiveDirectory
Add-ADGroupMember
Adds one or more members to an Active Directory group.
Add-ADGroupMember [-Identity] <ADGroup> [-Members] <ADPrincipal[]> [-AuthType {Negotiate | Basic}] [-Credential
<PSCredential>] [-Partition <String>] [-PassThru] [-Server <String>] [-Confirm] [-WhatIf] [<CommonParameters>]
Get-ADGroupMember -Identity "CN=PerthUsers,OU=WA,DC=company,DC=pri"
Add-ADGroupMember -Identity "CN=PerthUsers,OU=WA,DC=company,DC=pri" -Members "John.Smith"
Get-ADGroupMember -Identity "CN=PerthUsers,OU=WA,DC=company,DC=pri"
distinguishedName : CN=John.Smith,OU=NSW,DC=company,DC=pri
name : John.Smith
objectClass : user
objectGUID : a6e7fc6d-2049-44c8-b606-0a9d72ff2f5c
SamAccountName : John.Smith
SID : S-1-5-21-1973040400-4026026656-3317648685-1388
Code Used to create my lab domain
The original version of this is about 8 years old it is not the way I would do this now. None the less it does go through all the steps of creating a domain controller, setting up an OU structure, populating the domain with user accounts, creating groups, assigning users to groups, creating group policies and importing setting to those group policies, creating home folders and assigning ACL's to those folders.
To use my script you need the following files
PS C:\BuildDC> Get-ChildItem
Directory: C:\BuildDC
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 9/06/2020 10:33 AM {0B45FE31-85C1-476A-A16E-65A05B6487EB}
d----- 9/06/2020 10:33 AM {770BCE23-DABC-4DF5-A34F-9EE92958DFE0}
d----- 9/06/2020 10:33 AM {C5955D07-9FCE-464C-8041-DBECE27A62E4}
-a---- 9/06/2020 10:41 AM 8 1.txt
-a---- 8/02/2019 1:58 PM (1646) manifest.xml
-a---- 8/02/2019 2:02 PM 5274 New-CompanyDomain.ps1
-a---- 23/01/2019 1:04 PM (11722) useraccounts.csv
I have three exported group policies a file called 1.txt which contains only the number 1 only, the manifest from the group policies my script and a csv containing user accounts
Firstname,Lastname,path
Adam,Smith1,"ou=QLD,dc=company,dc=pri"
Adam,Smith2,"ou=NSW,dc=company,dc=pri"
Adam,Smith3,"ou=VIC,dc=company,dc=pri"
The way I designed the script to run is copy the folder to the root of the C drive.
Open it in the ISE on the server click the run button let it reboot and change 1.txt from 1 to 2.
Repeat the process a couple more times then highlight the first block after the break statement in the script and press f8
Repeat for the other blocks until finished.
The script looks like this
function New-PrepareForAD {
param($ADServername)
net user administrator P@ssw0rd
Rename-Computer $ADServername
Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
Install-WindowsFeature RSAT-AD-Tools -IncludeAllSubFeature
"2" | out-file c:\BuildDC\1.txt
Restart-Computer
}
function New-LabDomain {
Import-Module ADDSDeployment
$param = @{'CreateDnsDelegation'=$false;
'DatabasePath'="C:\Windows\NTDS";
'DomainName'='company.pri';
'DomainNetbiosName'='company';
'forestmode'='win2012r2';
'installdns'=$true;
'logpath'="C:\Windows\NTDS";
'NoRebootOnCompletion'=$true;
'confirm'=$false
}
Install-ADDSForest @param -SafeModeAdministratorPassword (convertTo-SecureString -AsPlainText "P@ssw0rd" -Force )
'3' | Out-File c:\buildDC\1.txt
Restart-Computer
}
function New-OUs {
New-ADOrganizationalUnit -Name:"NSW" -Path:"DC=company,DC=pri" -ProtectedFromAccidentalDeletion:$true -Server:"DC.company.pri"
New-ADOrganizationalUnit -Name:"QLD" -Path:"DC=company,DC=pri" -ProtectedFromAccidentalDeletion:$true -Server:"DC.company.pri"
New-ADOrganizationalUnit -Name:"VIC" -Path:"DC=company,DC=pri" -ProtectedFromAccidentalDeletion:$true -Server:"DC.company.pri"
New-PopulateAD
}
function New-PopulateAD {
$users = import-csv C:\BuildDC\useraccounts.csv
foreach($user in $users){
$a = $user.Firstname
$b = $user.lastname
$c = "$a.$b"
$d = $a + ' ' + $b
$e = $c + '@lab.pri'
New-Item -Path 'c:\home' -name $c -itemtype directory
switch($users.path)
{
"ou=QLD,dc=company,dc=pri"{$city = 'Brisbane'}
"ou=NSW,dc=company,dc=pri"{$city = 'Sydney'}
"ou=VIC,dc=company,dc=pri"{$city = 'Melbourne'}
}
switch($users.path)
{
"ou=QLD,dc=company,dc=pri"{$State = 'Queensland'}
"ou=NSW,dc=company,dc=pri"{$State = 'New South Wales'}
"ou=VIC,dc=company,dc=pri"{$State = 'Victoria'}
}
$opath = $user.path
New-ADUser -Name $c -AccountPassword (convertTo-SecureString -AsPlainText "P@ssw0rd" -Force ) `
-City $city -Company 'company' -DisplayName $d -EmailAddress $e -GivenName $a `
-HomeDirectory "c:\home\$c" -HomeDrive H -PasswordNeverExpires $true -Path $opath `
-SamAccountName $c -State $State -Surname $b -Enabled $true -Country AU
}
}
function Set-PFACLs {
$users = import-csv C:\BuildDC\useraccounts.csv
foreach($user in $users){
$fn = $user.Firstname
$ln = $user.lastname
$a = "$fn.$ln"
Write-Output "icacls --% c:\home\$a /grant company\$a`:(OI)(CI)(M)" -OutVariable b
powershell $b
}
}
function Set-PFSitesSubnets {
New-ADReplicationSite -Description "NSW site sydney office" -Name "NSW"
New-ADReplicationSite -Description "QLD site Brisbance office" -Name "QLD"
New-ADReplicationSite -Description "VIC site Melbourne office" -Name "VIC"
New-ADReplicationSubnet -Name "10.10.1.0/24" -Site NSW -Location "Sydney,NSW"
New-ADReplicationSubnet -Name "10.10.2.0/24" -Site QLD -Location "Brisbane,QLD"
New-ADReplicationSubnet -Name "10.10.3.0/24" -Site VIC -Location "Melbourne,VIC"
}
$a = get-content c:\BuildDC\1.txt
switch ($a){
1 {New-PrepareForAD -ADServername DC}
2 {New-LabDomain}
3 {New-OUs ; Set-PFACLs; Set-PFSitesSubnets}
}
Break;
#You should be able to rebuild all groups and group policies and set the policies to the correct OUs
#Importing the actual settings of groups policies can not be done with powershell so they should be documenting and
#backed up to a place not in the AD
New-ADGroup -Name MelbourneUsers -GroupScope Global -Path "OU=VIC,DC=company,DC=pri"
$vmembers = (Get-ADUser -SearchBase "OU=VIC,DC=company,DC=pri" -Filter *).samaccountname
foreach($vmember in $vmembers){
Add-ADGroupMember -Members $vmember -Identity MelbourneUsers
}
New-ADGroup -Name SydneyUsers -GroupScope Global -Path "OU=NSW,DC=company,DC=pri"
$smembers = (Get-ADUser -SearchBase "OU=NSW,DC=company,DC=pri" -Filter *).samaccountname
foreach($smember in $smembers){
Add-ADGroupMember -Members $Smember -Identity SydneyUsers
}
New-ADGroup -Name BrisbaneUsers -GroupScope Global -Path "OU=QLD,DC=company,DC=pri"
$bmembers = (Get-ADUser -SearchBase "OU=QLD,DC=company,DC=pri" -Filter *).samaccountname
foreach($bmember in $bmembers){
Add-ADGroupMember -Members $bmember -Identity BrisbaneUsers
}
New-GPO -Name VICUsers -Comment "GPO for Melbourne Users"
New-GPO -Name QLDUsers -Comment "GPO for Queensland Users"
New-GPO -Name NSWUsers -Comment "GPO for NSW Users"
new-GPLink -name VICUsers -Target "OU=VIC,DC=company,DC=pri" -LinkEnabled Yes
new-GPLink -name QLDUsers -Target "OU=QLD,DC=company,DC=pri" -LinkEnabled Yes
new-GPLink -name NSWUsers -Target "OU=NSW,DC=company,DC=pri" -LinkEnabled Yes
Import-GPO -BackupGpoName NSWUsers -TargetName NSWUsers -Path C:\BuildDC
Import-GPO -BackupGpoName QLDUsers -TargetName QLDUsers -Path C:\BuildDC
Import-GPO -BackupGpoName VICUsers -TargetName VICUsers -Path C:\BuildDC
Enabling the recycle bin in Active Directory
There is really no reason not to set the recycle bin and it can save a lot of effort restoring accidental deletions
Although is it really easy to do now using the GUI when it first came out you needed to use PowerShell and the command is:
Enable-ADOptionalFeature -Identity "Recycle Bin Feature" -Scope ForestOrConfigurationSet -Target (Get-ADForest).rootdomain` -Server (Get-ADForest).domainnamingmaster -Confirm:$false
Adding a UPN using PowerShell
Get-ADForest | Set-ADForest -UPNSuffixes @{add='pinkdolphinterritory.com'}
