Syed Jahanzaib Personal Blog to Share Knowledge !

February 15, 2017

Personnel Notes on Active Directory


audit reporting in excel.PNG

Recently our IT dept was going through yearly Audit and we had to provide active directory details asked by the auditor team. I used few commands that saved lot of time to get our desired/trimmed results. and since I mostly use my Ubuntu box to manage large portion of my network, therefore i made few scripts using these commands to be executed from linux based pc.

I had to repeat the whole search criteria every time by refreshing the memory/google, and since it this is a repeating task , and I had to go through the search process every time, I thought to make all these documented so that I can retrieve them when required.

I also linked these scripts with the Linux base WEBMIN, so they can be called by GUI for support staff as well.

Most queries are executed from Linux base system using WINEXE, if you are using windows only then you may want to modify it as required, I am just showing an way of executing AD commands via powershell using *nix 🙂 . The most annoyed thing was to wrap the commands in single/double quotes along with other parameters to make it single liner execution bomb.

Some of following commands are wrapped for linux base execution, and some are common powershell commands, make sure to run import-module activedirectory command before querying AD instance]

Make sure to change the IP / credentials as required.

#Total number of user accounts in AD
PS> (Get-ADUser -filter *).count

#Total number of user accounts in an OU
(Get-ADUser -filter * -searchbase "OU=Test, OU=MyCompany, DC=Domain, DC=Local").count
#Replace the SearchBase with your own OU path.

#Total number of enabled/disabled accounts in AD
(Get-AdUser -filter * |Where {$_.enabled -eq "True"}).count
(Get-ADUser -filter * |Where {$_.enabled -ne "False"}).count

#Total number of user accounts in a Group
(Get-ADGroupMember -Identity "Administrators").count


Get user Password Expiration Date:

List all users, password last set date and if the password never expires.

Net user AD_USERNAME /domain]

Display User name and upcoming Password expiration …

Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

How to Get AD Users Password Expiration Date

Script for linux to fetch users list not logged in from past XX Days & Email it to admin (Worked on 2008)

Will not work with 2012/2016

#set -x
# This bash script will query remote lotus domino mail server storage using Powershell Commands.
# It will send report via email with erelevant details, Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017


# GMAIL DETAILS to send EMAIL alert
# Add recipient email address below

MSG_SUB="$COMPANY - Domain users not logged in last $DAYS days Report @ $DATE"
MSG_BODY="$COMPANY - $SRVNAME - List of domain users not logged in last $DAYS days

FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin

echo "

#Full size of Lotus ARCHIVE Folder only
USER_LIST=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "$DaysInactive = $DAYS; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate"'`
echo "List of $COMPANY Domain users who have not logged since past $DAYS ..."


echo "----------------------------------------------

sendemail -u "$MSG_SUB" -o tls=yes -s -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

Command to get all Active Directory Users with particular information [April-2019]

Get-ADUser -Filter * -Properties * | select Name,UserPrincipalName,Created,Enabled,LastLogonDate |Out-File .\temp\zaib-ad-users-list.txt

24 September 2019 – PWC audit *** Zaib

Export all AD users with particular fields required by PWC audit. Handy cmd I made,

Get-ADUser -Filter * -Properties * | select Name,UserPrincipalName,Created,Enabled,LastLogonDate,@{n='pwdLastSet';e={[DateTime]::FromFileTime($_.pwdLastSet)}} |export-csv c:\temp\zaib-ad-users-list.csv


  • Command to Display Total Number Of Active Directory Users [Including disabled/enabled accounts as well]
(get-aduser -filter *).count
get-aduser -filter * | measure-object | select-object count
  • Command to Display Total Number Of Active Directory Users [Only ENABLED]
(get-aduser -filter *|where {$_.enabled -eq "True"}).count
get-aduser -filter 'enabled -eq $true' | measure-object | select-object count
  • Command to Display Total Number Of Active Directory Users [Only DISABLED]
(get-aduser -filter *|where {$_.enabled -ne "False"}).count
  • Command to Display All users along with every detail / information
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties *"'
  • Command to display only single user information as mentioned
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; Get-ADUser ZAIB-USER-NAME -Properties *"'
  • Command to display only specific information
winexe -U DOMAIN/ADMIN%"PASSWORD" // 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate"' 
  • Show Members from SPECIFIC GROUP group only
dsquery group -samid "Domain Admins" | dsget group -members | dsget user
  • Show specific user OU & MemberOf
$user = get-aduser USERNAME;
$memb = (GET-ADUSER –Identity USERNAME –Properties MemberOf | Select-Object MemberOf).MemberOf -replace "DC=DCNAME*" -replace "CN="
$uo = $user.distinguishedname.substring($user.distinguishedname.indexof(",") + 1,$user.distinguishedname.Length - $user.distinguishedname.indexof(",") - 1)
write-host "$($user.Name) = $($uo.split(',')[0])"
echo "Member of:" $memb
  • Command to get all users and show only following fields


winexe -U DOMAIN/ID%PASSWORD // 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties * | select
UserPrincipalName,Created,Enabled,MemberOf |Format-Table -Property * -AutoSize | Out-String -Width 4096 | Out-File c:\1.txt"'
  • Query for speciifc User belongs to which groups
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; (GET-ADUSER –Identity zaib.user –Properties MemberOf |  Select-Object MemberOf).MemberOf"'
  • Get Members List of specific Group
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; Get-ADGroupMember "'"'Domain Admins'"' |Select name,distinguishedName |  Format-Table -AutoSize"'
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; Get-ADGroupMember "'"'Limited Internet Facility Group'"' |Select sAMAccountName| Format-Table -AutoSize"'
  • Show All Users Created Dated Only using PowerShell
winexe -U DOMAIN/ID%PASSWORD // 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties Created | Select-Object Name,Created | Sort-Object Created"'
  • Show Users created in Last 30 days
winexe -U DOMAIN/ID%PASSWORD // 'powershell.exe -command "import-module activedirectory; $When = ((Get-Date).AddDays(-30)).Date; Get-ADUser -Filter {whenCreated -ge $When} -Properties whenCreated"'
  • Show Users created in specific after DATE RANGE
Get-ADUser -Filter * -properties whencreated | ? { $_.whenCreated -ge (get-date "January 1, 2017") -and  $_.whenCreated -le (get-date "January 31, 2017")} |Select Samaccountname,whenCreated,office 
  • Show Users created in specific after DATE RANGE
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory;Get-ADUser -Filter * -properties whencreated | ? { $_.whenCreated -ge (get-date "'"'January 1, 2017'"') -and $_.whenCreated -le (get-date "'"'January 31, 2017'"')} |Select Samaccountname,whenCreated,office"'
  • Show Users DELETED in specific DATA RANGE … [powershell commands]
[datetime]$StartTime = "1/1/2017"
[datetime]$EndTime = "1/15/2017"
Get-ADObject -Filter {(isdeleted -eq $true) -and (name -ne "Deleted Objects") -and (ObjectClass -eq "user")} -includeDeletedObjects -property whenChanged | Where-Object {$_.whenChanged -ge $StartTime -and $_.whenChanged -le $EndTime} |Select Name,whenChanged |Format-Table
  • Show DISABLED Users Only …
#Method 1 using PS
winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; search-adaccount -UsersOnly -AccountDisabled | select samAccountName"'
  • Show users who have not logged in Since 60 days

winexe -U DOMAIN/ID%PASS // 'powershell.exe -command "import-module activedirectory; $domain = "DOMAIN-NAME"; $DaysInactive = 60; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp"'
# Method 3 using dsquery
dsquery user "dc=Your_Domain_Name" -inactive 2

  • Show DISABLED Users Only using DSQUERY
dsquery user -disabled | dsget user -display -email -dept -title
  • Show Only Specific User Details [ Method#2]
winexe -U DOMAIN/ID%PASSWORD // 'Net user ZAIB /domain"'

  • Get DHCP info from server to acquire some customized report
# is our scope
winexe -U DC/ID%PASSWRORD // 'netsh dhcp server scope show clients 1'
  • Dump DHCP SERVER DETAILS IN FILE for some specific purpose, i required to get mobile devices list
# Dump DHCP
winexe -U DC/ID%PASSWD // 'netsh dhcp server \\DCSERVERNAME dump' > /tmp/dhcp_temp.txt
cat /tmp/dhcp_temp.txt | grep 101.11.14. | awk '{ print $11,$12}' | sed -e 's/""//g' -e 's/""//g' -e 's/"//g' -e 's/ BOTH//g' | sed '/ \r/d' | sort
cat /tmp/dhcp_temp.txt | grep 101.11.14. | awk '{ print $11,$12}' | sed -e 's/""//g' -e 's/""//g' -e 's/"//g' -e 's/ BOTH//g' | sed '/ \r/d' | sort | wc -l


Extract Users from Group with name/description only to CSV file

Get-ADGroupMember -Identity "Full Internet Access Group" |Where-Object { $_.objectClass -eq 'user' } |Get-ADUser -Properties * | Select UserPrincipal
Name,Description |Out-File .\temp\full2.csv

Add/Replace AD attributes via powershell cmd

SET-ADUSER ali.akbar –replace @{userPrincipalName=""}
SET-ADUSER ali.akbar –replace @{mail=""}
SET-ADUSER ali.akbar –replace @{mailNickname="test.user"}
SET-ADUSER ali.akbar –replace @{targetAddress=""}
SET-ADUSER ali.akbar –replace @{proxyAddresses=""}

Syed Jahanzaib

%d bloggers like this: