Enable Active Directory module for Windows Powershell in workstation

Enable Active Directory Modules in workstation


Work Instruction:
Open Control Panel and navigate to below path
Programs > Programs and Features > Trun Windows features on or off >Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools > Active Directory module for Windows Powershell.
Click 'OK' button
once loading is completed, open powershell and run below cmd to see if modules are loading.
PS>import-module activedirectory



Powershell script to create Bulk User Accounts and add then to AD group in parllel.

Powershell script to create Bulk User Accounts and add them to AD group in parllel.
Purpose: Request to Create bulk user accounts like 100+ for testing and add to AD Group
Comment for improvement


Script:
Import-Module ActiveDirectory
$totalusers = <Provide the no of users you want to create, Ex: 50>
for ($i=0; $i -lt $totalusers; $i++)
 {
  $userID = "{0:00}" -f ($i + 1)
//below is cmd to user account name like Test01, Test02...etc; change the cmd according to the format.
  $userName = "Test$userID"

  Write-Host "Creating AD user" ($i + 1) "of" $totalusers ":" $userName
New-ADUser -Name $userName -Path  "<OU path to create user Account;ex:CN=Users,DC=XX,DC=XXXXX,DC=XXX" -SamAccountName $userName -AccountPassword (ConvertTo-SecureString "<EnterPassword>" -AsPlainText -Force) -ChangePasswordAtLogon $false -Enabled $true -Description "Description of the Account" -Notes "<any notes if you would like to add>" -PasswordNeverExpires $True -UserPrincipalName  $_."userName" + "@<DomainName,ex:XXXXXX.com>" -GivenName $userName -DisplayName $userName
//you can comment out below line, if you wouldn't like to add user to any ad group
 Add-ADGroupMember "<AD group name to add User to>" $userName;
}

Powershell Script to Replicate OU Structure from Source OU to Target OU.

Powershell Script to Replicate OU Structure from Source OU to Target OU.


Purpose of the Script: i wrote the script to replicate the OU & Sub OU Structure from one OU to Another OU, the below script will take a backup of Source and Target OU before and after replication to CSV file.
Note: test it in test OU's before running in Prod OUs, it worked like charming.
Post comments for improvements.


Script:
import-module activedirectory
####Current OU Structure in Source & target for reference#####
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU1,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./BeforeSourceOUReplication.csv
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU2,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./BeforeTargetOUReplication.csv
##################
$sourceOU = "<OU Path; ex: OU=TestOU1,DC=XX,DC=XXXXX,DC=com>"
$destinationOU = "<OU Path; ex: OU=TestOU2,DC=XX,DC=XXXXX,DC=com>"
##################
#--------Main
##################
$adPath= "LDAP://" + $destinationOU
#Create OUs
$objDomain=New-Object System.DirectoryServices.DirectoryEntry($adPath)
$ObjSearch=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)
[array] $OUs = @()
$OUs = dsquery * $sourceOU -Filter "(objectCategory=organizationalUnit)" -limit 0
$OUsorted = $OUs | sort-object { $_.Length}
for ($k=0; $k -le $OUsorted.Count -1; $k++)
{
    $OUtoCreate = ($OUsorted[$k] -replace $sourceOU,$destinationOU).ToString()
    $OUSearch = ($OUtoCreate -replace '"',"").ToString()
    $ObjSearch.Filter = "(&(objectCategory=organizationalUnit)(distinguishedName="+ $OUSearch + "))"
    $allSearchResult = $ObjSearch.FindAll()
    if ($allSearchResult.Count -eq 1)
    {
        "No changes were done on = " + $OUtoCreate
    }
    else
    {
        dsadd ou $OUtoCreate
        "OU Creation = " + $OUtoCreate
    }
}
####OU Structure after replication in Source & target for validation####
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU1,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./AfterSourceOUReplication.csv
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU2,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./AfterTargetOUReplication.csv

Powershell Script for AD GPO Replication

Powershell Script for AD GPO Replication:


Purpose: I got 1 project request that i have to replicate the current OU Structure to Another location/OU in same domain. So i wrote a script to replicate the OU structure, later customer requested to link the GPOs as it was in Source OU to target OU. so i wrote below script.
OU replication powershell script i will post in another post.


Ex:
SourceOU:
TestOU1
 GPOLink1
 GPOLink1
 OU2
 GPOLink3
 GPOLink4
TargetOU:
TestOU2
 GPOLink1
 GPOLink1
 OU2
 GPOLink3
 GPOLink4


Script:
# Import the Active Directory module
import-module activedirectory
# Import the Group Policy module
Import-Module GroupPolicy
# Source for GPO links
$Source = "<OU Path;Ex: OU=Test1,DC=XX,DC=XXXXX,DC=com>"
# Target where we want to set the new links
$Target = "<OU Path;Ex: OU=Test2,DC=XX,DC=XXXXX,DC=com>"
##################
#Main Function
##################
[array] $OUs = @()
$OUs = dsquery * $Source -Filter "(objectCategory=organizationalUnit)" -limit 0
$OUsorted = $OUs | sort-object { $_.Length}
for ($k=0; $k -le $OUsorted.Count -1; $k++)
{
#$OUsorted[4]
    $sourceOuSearck = $OUsorted[$k].ToString()
    $sourceOulink = ($sourceOuSearck -replace '"',"").ToString()
    $linked = (Get-GPInheritance -Target $sourceOulink).gpolinks
    $targetlinkpoint = ($OUsorted[$k] -replace $Source,$Target).ToString()
    $TargetOULink = ($targetlinkpoint -replace '"',"").ToString()
   
    # Loop through each GPO and link it to the target
     foreach ($link in $linked)
     {
            $guid = $link.GPOId
            $order = $link.Order
            $enabled = $link.Enabled
        if ($enabled)
        {
            $enabled = "Yes"
                # Create the link on the target
                New-GPLink -Guid $guid -Target $TargetOULink -LinkEnabled $enabled -confirm:$false
                # Set the link order on the target
                Set-GPLink -Guid $guid -Target $TargetOULink -Order $order -confirm:$false
        }
        else
        {
            $enabled = "No"
        }
    }
}

LDAP User authrntication failed on 3rd party application (or) DCdiag failed return value = 81 (or) Naming information cannot be located.

Error's:
LDAP User authentication failed on 3rd party application connecting to AD for authentication.
DCdiag CMD failed.
Naming information cannot be located


Issue:
Customer reported Unable to login to tools applications console's.


Resolution:

First check the replication status, using below cmd
CMD>> repadmin /showrepl * /csv >showrepl.csv
run the above cmd on any domain controller, it will generate a report, check if you have any replication error and when the last sync was happened in the report.
if some error reported, then note the destination & source DC name.
then go to the domain controller rdp, run the below cmd in Command line.
CMD >> dcdiag
if you get below error message, then there is authentication issue on that domain controller.
fix: reboot the DC and re-run "dcdiag" CMD, if it is succussfull, then issue is resolved.
in our case, it was because some patch installed in the DC, which caused the services hanging.


Error:
Performing initial setup:
   Trying to find home server...
   Home Server = XXXXXXXXX
   Ldap search capability attribute search failed on server XXXXXXXXX,
   return value = 81

Error: Call "StorageResourceManager.RecommendDatastores" for object "StorageResourceManager" on vCenter Server "" failed.

Issue: Unable to Migrate a VM from 1 Datestore to another datastore, after the validation step in migration, the next window is keep process/blank screen and getting below error message. (Vcenter Client)


Error: Call "StorageResourceManager.RecommendDatastores" for object "StorageResourceManager" on vCenter Server "<VCenterServer>" failed.


Fix:
The issue is with the VM version & vSphere Client Version, try the migration from VMware vSphere Web Client, it will work


Url: https://<vCenterServerIP>:9443/vsphere-client/


In case, i was able to migrate the VM from VMware vSphere Web Client.

General ESXi Commands

1. How to Retrieves the hard disks of the virtual machine named VM
CMD> Get-HardDisk -VM <VirtualMachine Name>


2. How to List all Volumes on ESXi host
CMD> esxcfg-volume –l


3. How to Persistant Mount the Volume from CLI.
CMD> esxcfg-volume –M "<DatastoreName>"

General Commands in Powershell


PS C:\> Get-WmiObject -Class win32_OperatingSystem -ComputerName <>
SystemDirectory : C:\Windows\system32
Organization    : Org name
BuildNumber     : 7601
RegisteredUser  : Org Name
SerialNumber    : XXXXX-XXX-XXXXXXX-XXXXX
Version         : 6.1.76PS
C:\> $PSVersionTable
Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.12.1


#####List available module########
> Get-Module -ListAvailable
ModuleType Name                      ExportedCommands                                                          
---------- ----                      ----------------                                                          
Manifest   AppLocker                 {}                                                                        
Manifest   BitsTransfer              {}                                                                        
Manifest   PSDiagnostics             {}                                                                        
Manifest   TroubleshootingPack       {}

######Import AD Module#######
import-module activedirectory


backtick `

General Linux Commands

//Scan the Scsi Controller (note: if you host has)
echo "- - -" > /sys/class/scsi_host/host0/scan


//check the newly added disks
fdisk -l | grep -i ^Disk


//check the partation
fdisk -l <ex: /dev/sdf>


//create the partation
fdisk <ex: /dev/sdf>
n
p
v
p
w


//make filesystem
mkfs.ext3 <ex: /dev/sdf1>


//Check fstab
cat /etc/fstab


//check permission
ls -alh </filesystem path>


//Find a file
find / -name filename

Zero or Dead space reclaim on ESXi Host for EMC Storage

Note: enable ssh on ESXi Host & login to root via Putty & execute below commands.
1. List all connected volumes/datastores/LUNs in ESXi host
>> cd /vmfs/volumes/
>> ls
copy the list of volumes in separate notepad


2. CMD to run the reclaim manually on individual LUN(or)datastore
cd /vmfs/volumes/<DatastoreName>
//then execute below cmd to reclaim dead space (value can be range from 0 upto 99)
vmkfstools -y 70
vmkfstools -y 90
(why i run 2 times is, just to avoid datastore hangs and its one of the recommended best practice).

SAN Zoning in Cisco Switch


Create FCalias name for the new HBA WWPN
Switch1(config)# fcalias name <Name/ex:Servername_Hba> vsan <vsanID>
Switch1(config-fcalias)# member pwwn <20:00:00:xx:xx:xx:xx:xx>
Switch1(config-fcalias)# exit
Create new Zone Name (ServerName_hba0-ArrayName_Port) and add members into it:
Switch1(config)# zone name <ServerName_hba-ArrayName_Port> vsan <vsanID>
Switch1(config-zone)# member fcalias <AliasName/ServerName_hba0>
Switch1(config-zone)# member fcalias <AliasName/ArrayName_FAPort>
Switch1(config-zone)# exit
Add zones to zone set:
Switch1(config)# zoneset name <ZoneSetName> vsan <vsanID>
Switch1(config-zoneset)# member <ServerName_hba0-ArrayName_Port>
Switch1(config-zoneset)# member <ServerName_hba1-ArrayName_Port>
Switch1(config-zoneset)# exit

Activate zoneset:
Switch1(config)# zoneset activate name <ZoneSetName> vsan <vsanID>
Commit changes:
Switch1(config)# zone commit vsan <vsanID>
Commit operation initiated. Check zone status
Switch1(config)# exit
Check Zone Status:
Switch1(config)# sh zone status
Check active zone:
Switch1(config)# sh zone active
We can find newly created Zone in this active zone
copy startup-config running-config

Symrdf Commands

<Ping cmd to check remote array connectivity>
symrdf ping -sid <SymmID>
<Cmd to check list of RDF Ports in Local/Remote array>
symcfg -sid <SymmID> list -RA all
<List of RDF Devices>
symrdf -sid <SymmID> list > c:/rdflist.txt
<Cmd to check cylinder size source>
symdev -sid <SymmID> show <XXXX> | findstr Cylinder
<Cretae RDF Group>
symrdf -sid <SymmID> -label <RDFGroupName> -dir <RDFPorts/ex:6h,11h> -rdfg <GroupID> -remote_sid <RemoteSymmID> -remote_dir <RDFPorts/ex:7d,10d> -remote_rdfg <RemoteGroupID> addgrp
<Creating RDF Pair>
symrdf -sid <SymmID> -rdfg <GroupID> -type rdf1 -file <FilePath>.txt createpair -establish
<Checking>
symrdf -sid <SymmID> -rdfg <GroupID> -type rdf1 -file <FilePath>.txt Query
<Checking the time to get synced completely>
symrdf -sid <SymmID> -rdfg <GroupID> -type rdf1 -file <FilePath>.txt Query -t 30 -c 5
<set devices to set mode>
symrdf -sid <SymmID> -rdfg <GroupID> -type rdf1 -file <FilePath>.txt set mode sync
<this is split the replication>
symrdf -sid <SymmID> -rdfg <GroupID> -type rdf1 -file <FilePath>.txt split
<Force suspend>
symrdf -sid <SymmID> -rdfg <GroupID> -f <FilePath>.txt suspend -force -symforce

//set link limbo - feature allows you to set a specific length of time for Enginuity to wait when a down link is detected before updating the link status. If the link status is still Not Ready after the link limbo time expires, devices are marked Not Ready to the link.
symrdf -sid <SymmID> -rdfg <GroupID> set link_limbo 120
<list the devices in rdfg >
symrdf -sid <SymmID> -rdfg <GroupID> list > <FilePath>.txt

Day to Day CMDs for Active Directory Directory Service

1. How to find which domain contoller the Client work station/Server is connected.
open command prompt (cmd.exe)
CMD>> echo %logonserver%


2. How the check the FSMO roles of the connected domain
open command prompt (cmd.exe)
CMD>> netdom query FSMO


3. NTP Troubleshoot:
check the status of NTP in local server
CMD> w32tm /query /status


Check weather server/DC able to get time from respective NTP Server
CMD> w32tm /stripchart /computer:<NTP Server Name>


After you update the NTP setting in local GPO, run below command to update the settings.
CMD> w32tm.exe /config /update


Stop the Time service on local server
CMD> net stop w32time


Start the Time service on local server
CMD> net start w32time


4. How to find the LDAP protocal port number
Open Cmd Prompt & Type below cmds
CMD> nslookup
CMD> set type=1
CMD> _ldap._tcp.dc._msdcs.domainname.com


5. View Local System GPO Settings
Open Run>> RSOP.msc
(or)
CMD> gpresults /R
CMD> gpresults /SCOPE COMPUTER /R


6. How to Check and Release the inactive session on a remote server
//to list all session
CMD> qwinsta /server:<RemoteServerName>
(or)
CMD> quser /server:<RemoteServerName>

//to close inactive session (you will get session id when you list the session on server using above cmd)
CMD>>rwinsta <SessionID> /server:<ServerName>
(or)
logoff <SessionID> /server:<RemoteServername>


7. How to Update the GPO Setting Forcefully on local machine
CMD> gpupdate /force

8. How to Get Local Computer Name
CMD> echo %computername%
or
CMD> hostname


9. How to Rename remote Computer (recommemded to restart the computer after name change).
CMD> netdom renamecomputer <RemoteComputerName/LocalComputerName> /NewName:<NewComputerName>


10. How to List all interface Details
CMD> netsh interface IPv4 show interfaces


11. How to set IP for an IPv4 interface
CMD> netsh interface IPv4 set address name=<Idx Number> source=static address=<xxx.xxx.xxx.xxx> mask=<xxx.xxx.xxx.xxx> gateway=<xxx.xxx.xxx.xxx>


12. How to set IP for an IPv6 interface
CMD> netsh interface IPv6 set address interface=<Idx Number> address=<ex:fd00:0:0:1::2>


13. How to set DNS server
CMD> netsh interface IPv4 add dnsserver name=<Idx Number> address=<DNS address x.x.x.x> index=1


14. How to Set loopback connection
CMD> netsh interface IPv4 add dnsserver name=<Idx Number> address=<DNS address 127.0.0.1> index=2


15. How to list of Roles & Features Installed on Windows Server
CMD> oclist | more


16. How to Run a role in AD
CMD> start /w ocsetup DNS-Server-Core-Role
(/W -  will wait until the window is complete)


17. How to Reboot the machine through Cli
CMD> shutdown /r /t 2


18. how to Check all IP Details
CMD> ipconfig /all | more


19. How to connect the network drive
CMD> net use * \\NetworkShareLocation


20. How to Copy file to local directory
CMD> copy <sourcefile> <targetfile>


21. How to Open a file in notepad
CMD> notepad <filelocation>


22. How to Promoting Domain Controller using answer file
>>dcpromo /unattend:<filelocation>.txt


How to Promoting Domain Controller using cmd
>>dcpromo /replicationOrnewDomain:replica /replicationDomainDNSName:<domain.local> /ConfirmGC:yes /userdomain:<domain.local> /UserName=administrator /Password=<PSW> /SafeModeAdminPassword=<PSW>

###KB Articals###
//fill list of DC Promo settings
http://support.microsoft.com/kb/947034


23. How to LDF file Export Group users Information.
CMD> ldifde -f C:\Temp\Exportuser.ldf -server <DomainName> -r "(&(objectClass=User)(DC=XXXX,DC=XXXX,DC=com))" -l "sAMAccountName,givenName,sn"


24. How to Generate KeyTab File
CMD> ktpass /out <FileName>.keytab /princ <UserName>@<Domain> /pass <password> /ptype KRB5_NT_PRINCIPAL /out username.keytab



##########PowerShell CMDs##################
Note: To Run the below cmds, you should have powershell installed and imported the Active Directory Module (CMD to Import Active Directory Module: PS>>Import-Module ActiveDirectory)


Powershell Cmd: How to Check Schema Version
PS> Get-ADObject "cn=schema,cn=configuration,dc=XXXXX,dc=COM" -properties objectversion


Powershell Cmd: How to find Account Name using SID
PS> $objSID = New-Object System.Security.Principal.SecurityIdentifier ("S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXX-XXXXXX")
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objUser.Value


Powershell Cmd: How to export all OU info to Excel Sheet
PS> Get-ADOrganizationalUnit -server <DomainName> -Filter '*' -properties * | Select CanonicalName,DistinguishedName | export-csv "<FilePath>.csv"


Powershell Cmd: How to set the user should change password at next logon
PS> Set-ADUser -Identity "<AD ID/User Name>" -ChangePasswordAtLogon $true -server <DomainName>


Powershell Cmd: How to set the user account to expire on specific timestamp
PS> Set-ADAccountExpiration -Identity "<AD ID/User Name>" -DateTime '<TimeStamp ex: 1/19/2017 12:01:37 PM>' -server <DomainName>


Powershell Cmd: How to get AD User password last change, account expire date & last password change time.
Get-ADUser -Identity "<AD ID/User Name>"  -server <DomainName> -Properties AccountExpirationDate | Select-Object -Property SamAccountName, AccountExpirationDate, PasswordLastSet
if you installed "ActiveRoles Management shell for Active Directory"
PS> get-qaduser <Domain>\<AD ID> -properties *  | select pwdlastset, passwordexpires


Powershell Cmd: How create a AD Group in 'ActiveRoles Management shell for Active Directory'
PS> New-QADGroup -GroupScope <Universal -GroupType Security -Name '<New_AD_GroupName>' -samAccountName <New_AD_GroupName>' -Description '<Purpose of The Group>' -ParentContainer '<ex:OU=Groups,DC=XX,DC=XXXXX,DC=com>' -ManagedBy <Domain>\<Owner>


Powershell Cmd: How to get user group memberof info in 'ActiveRoles Management shell for Active Directory'
PS> Get-QADMemberOf <UserName> | select name


Powershell Cmd: how to see the powershell cmdlet syntax
PS> Get-Help Set-ADUser –detailed

Windows 10/7 AD Group properties error : "The properties for this item are not available error"



Error: "The properties for this item are not available error"
Cause: this issue is triggered by corrupted/missing/damaged registry keys.


Recommendation:
1. First of all, check if your Windows 10/7 system is up-to-date
2. if yes then, Go to Control Panel > Click 'Troubleshoot' > click 'Run maintenance tasks'
3. after that, Run 'System File Checker' >> run cmd.exe as administrator, type CMD>sfc /scannow
(The sfc /scannow command will scan all protected system files, and replace corrupted files with a cached copy that is located in a compressed folder at %WinDir%\System32\dllcache.)


if the scan was successfull and no error message or error message like below is reported, then re-image the OS.


"Verification 100% complete.
Windows Resource Protection found corrupt files but was unable to fix some of them."