Syed Jahanzaib Personal Blog to Share Knowledge !

February 15, 2017

Personnel Notes on Active Directory


ad

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

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/temp
#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
COMPANY="ZAIB"
SRVNAME="XXXXX"
IP="10.0.0.1"
DOMAIN="XXX"
PASS="XXXXX"
ID="XXXX"
TEMP_HOLDER="/tmp/domain_inactive_users_list.txt"
> $TEMP_HOLDER

DATE=`date`
DAYS="30"

# GMAIL DETAILS to send EMAIL alert
GMAILID="agpmonitor@gmail.com"
GMAILPASS="Welcome2agp"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

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
@ $DATE

"
FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" > $TEMP_HOLDER

#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 "$USER_LIST" >> $TEMP_HOLDER

echo "----------------------------------------------
$FOOTER" >> $TEMP_HOLDER

cat $TEMP_HOLDER
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -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
#OR
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
#OR
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 //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties *"'
  • Command to display only single user information as mentioned
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser ZAIB-USER-NAME -Properties *"'
  • Command to display only specific information
winexe -U DOMAIN/ADMIN%"PASSWORD" //10.0.0.1 '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

UserPrincipalName,Created,Enabled,MemberOf

winexe -U DOMAIN/ID%PASSWORD //10.0.0.1 '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 //10.0.0.1 '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 //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADGroupMember "'"'Domain Admins'"' |Select name,distinguishedName |  Format-Table -AutoSize"'
#OR
winexe -U DOMAIN/ID%PASS //10.0.0.1 '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 //10.0.0.1 '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 //10.0.0.1 '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 //10.0.0.1 '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 //10.0.0.1 '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 //10.0.0.1 '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 //10.0.0.1 'Net user ZAIB /domain"'

  • Get DHCP info from server to acquire some customized report
# 10.0.0.1 IS DOMAIN
# 101.0.0.0 is our scope
winexe -U DC/ID%PASSWRORD //10.0.0.1 'netsh dhcp server scope 101.0.0.0 show clients 1'
  • Dump DHCP SERVER DETAILS IN FILE for some specific purpose, i required to get mobile devices list
# Dump DHCP
# 101.11.11.5 IS DOMAIN
# 101.11.14. IS MOBILE DEVICES IP SERIES, SO WE ARE CATCHING IT
# 101.11.11.36 IS GATEWAY
# 101.11.11.6 IS OTHER GATEWAY
winexe -U DC/ID%PASSWD //101.11.11.5 '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/"101.11.11.6"//g' -e 's/"101.11.11.36"//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/"101.11.11.6"//g' -e 's/"101.11.11.36"//g' -e 's/"//g' -e 's/ BOTH//g' | sed '/ \r/d' | sort | wc -l

24-Oct-2018

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

Regard’s
Syed Jahanzaib

January 16, 2013

Backup Files via CMD/Batch/ntbackup Scripts [Personnel Notes]


Salam to All,

Following are few backup batch files that I have used at my office to perform backup operation using scheduled backup tasks. I am posting them just for reference so they can be used as archiving or possibly useful for others too having same task.


Backup from local folder to Remote Server and make log files [This was updated on 10-Oct-2019]

@echo off
cls
set MAPPATH=\\FILESERVER\FOLDER1
set MAPDRIVELETTER=N:
set MAPDRIVEFULLPATH=N:\
set BKPFOLDER=D:\BACKUP
set BKPFOLDERFULLPATH=D:\BACKUP
set DAYS=-30
set LOGFOLDER=c:\backup

echo This script is designed by Syed Jahanzaib / AGP IS Dept.
if not exist "%LOGFOLDER%" mkdir %LOGFOLDER%
echo %computername% - Backup Scrtip Start_Time %date% %time% >> %LOGFOLDER%\lastrun.txt

if exist %MAPDRIVELETTER% (
echo "%MAPDRIVELETTER% Map Drive is present. Deleting it first"
net use /delete /y %MAPDRIVELETTER%
)

echo "Mapping drive named %MAPDRIVELETTER% "
net use %MAPDRIVELETTER% %MAPPATH%

if exist %MAPDRIVELETTER% (
echo Map Drive named %MAPDRIVELETTER% is now mapped , moving forward ...
echo %computername% - Backup Scrtip Start_Time %date% %time% >> %MAPDRIVELETTER%\lastrun.txt
ECHO "Holding for 10 seconds ... and then start copying Data from %BKPFOLDERFULLPATH% TO \\agpnas1\hplc particular user related folder - and delete data older then %DAYS% days"
ping -n 10 127.0.0.1 > %LOGFOLDER%\null
Robocopy.exe *.* /s /e /w:0 /r:0 /LOG:%LOGFOLDER%\backup_log.txt /NP /FP /TEE /ts %BKPFOLDERFULLPATH% %MAPDRIVELETTER%

rem ** IF you want to delete files only insdie this path including files inside subfolders
rem forfiles /p "%BKPFOLDER%" /s /m *.* /d %DAYS% /c "cmd /c del /Q @path"
rem forfiles /p "%MAPDRIVEFULLPATH%" /s /m *.* /d %DAYS% /c "cmd /c del /Q @path"

rem ** IF you want to delete FOLDERS inside this path
echo "now deleteing folders older then %DAYS% days from %BKPFOLDER% and %MAPDRIVEFULLPATH% ..."

echo "Following folders will be deleted (if found older then %DAYS% day, else no folder name will be listed"
echo "Following folders will be deleted (if found older then %DAYS% day, else no folder name will be listed" >> %MAPDRIVELETTER%\lastrun.txt
echo "Following folders will be deleted (if found older then %DAYS% day, else no folder name will be listed" >> %LOGFOLDER%\lastrun.txt
forfiles /P %BKPFOLDER% /D %DAYS% /M * /C "cmd /C if @isdir==TRUE echo @path" >> %MAPDRIVELETTER%\lastrun.txt
forfiles /P %BKPFOLDER% /D %DAYS% /M * /C "cmd /C if @isdir==TRUE echo @path" >> %LOGFOLDER%\lastrun.txt
forfiles /P %BKPFOLDER% /D %DAYS% /M * /C "cmd /C if @isdir==TRUE rd /S /Q @path"
forfiles /P %MAPDRIVEFULLPATH% /D %DAYS% /M * /C "cmd /C if @isdir==TRUE rd /S /Q @path"

echo.
echo SCRIPT is finished .....
echo %computername% - Backup Scrtip End_Time %date% %time% >> %MAPDRIVELETTER%\lastrun.txt
echo %computername% - Backup Scrtip End_Time %date% %time% >> %LOGFOLDER%\lastrun.txt
echo *************************************************** >> %MAPDRIVELETTER%\lastrun.txt
echo *************************************************** >> %LOGFOLDER%\lastrun.txt
) ELSE (
echo "ERROR: UNABLE TO ACCESS mapped %MAPDRIVELETTER% DRIVE , PLEASE CHECK ...."
echo "ERROR: UNABLE TO ACCESS mapped %MAPDRIVELETTER% DRIVE , PLEASE CHECK ...."
echo "ERROR: UNABLE TO ACCESS mapped %MAPDRIVELETTER% DRIVE , PLEASE CHECK ...." >> %LOGFOLDER%\lastrun.txt
echo %computername% - Backup Scrtip End_Time %date% %time% >> %LOGFOLDER%\lastrun.txt
echo *************************************************** >> %LOGFOLDER%\lastrun.txt
)

 


MOVE folders (including files/subfolders) ¬†Older than X days to another location using legendary ROBOCOPY ūüėČ

robocopy C:\SOURCE_FOLDER_LOCATION   D:\TARGET_FOLDER_LOCATION   /s   /e   /MOVE   /minage:2

/s : includes Sub Folders / Files
/e : include Empty folders as well
/MOVE : after copying, delete matching data from source
/minage : set criteria in days

Change the minage:2 to your desired number of days.


DELETE FOLDERS OLDER THEN XX DAYS USING POWERSHELL
[Added 16th October, 2015]

To delete FOLDERS (including files or sub folders) older then X days, you can use following powershell command, fully tested with windows 2008

PowerShell -Command "& Get-ChildItem "D:\Data" | Where-Object {$_.PSIsContainer -and $_.LastWriteTime -le [System.DateTime]::Now.AddDays(-3)} | Remove-Item -Recurse -Force"

Move Files to another folder/drive using ROBOCOPY – Older then 365 Days


robocopy D:\Users\Syed_Jahanzaib  X:\Users\Syed_Jahanzaib_Archive /MOVE /MINAGE:365 /E

There is confusion here and elsewhere, I believe the following is correct:

  1. minage and maxage actually refer to the last modified date of the file (not creation date)
  2. minlad and maxlad actually refer to the last access date of the file.

 


NTBACKUP with EMAIL the LOGS and START/END Time Report

This Script will first backup the data defined in “backup-data” to Tape Drive (In my case it was IBM LTO-3) and then email the LOG to your defined email addresses (in “mail-to” section) It will also record the total time of the backup and will attache it to the email.

@echo off
rem # Syed Jahanzaib #
rem #######################################################
rem Setting various Descriptions via environment variables
rem #######################################################

setlocal enableextensions enabledelayedexpansion
set starttime=%time%
set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%
set logpath="C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\Windows NT\NTBackup\data"
set srvname=SERVER_X
set backup-data=C:\backup\Tape Backup of Different Data.bks
set description=SERVER_X - Autobackup Different Data
set jobname=SERVER_X - Tape Backup of Different Data
set attachment=C:\backup\SERVER_X-ntbackup-%dt%.txt
set mail-subject=SERVER_X-NTBACKUP LOG for Different Data
set mail-body=SERVER_X-NTBACKUP LOG for Different Data
set mail-to="aacable@hotmail.com","aacable@hotmail.com"
set footer=Automated Backup and Email Logs Script Created by Syed_Jahanzaib

rem ######################################
rem Starting Backup in IBM LTO3 Tape Drive
rem ######################################

c:\windows\system32\rsm.exe refresh /lf"IBM ULT3580-TD3 SCSI Sequential Device"
ping -r 9 127.0.0.1 >null
start /wait C:\WINDOWS\system32\ntbackup.exe backup "@%backup-data%" /n "%jobname%" /d "%description%" /j "%jobname%" /l:s /p "LTO Ultrium" /UM /v:no /r:yes /rs:no /hc:on /m normal

rem ############
rem NTBackup END
rem ############

rem ### Copy current date LOG to C:\backup
forfiles -p %logpath% -s -m *.log -d 0 -c "cmd /c copy @file %attachment%"

rem #########################
rem STart END Time Algorithm
rem #########################

ping -n 2 127.0.0.1 >nul: 2>nul:
set endtime=%time%
set total="echo Total   = %tot%"

set /a hrs=%endtime:~0,2%
set /a hrs=%hrs%-%starttime:~0,2%

set /a mins=%endtime:~3,2%
set /a mins=%mins%-%starttime:~3,2%

set /a secs=%endtime:~6,2%
set /a secs=%secs%-%starttime:~6,2%

if %secs% lss 0 (
    set /a secs=!secs!+60
    set /a mins=!mins!-1
)
if %mins% lss 0 (
    set /a mins=!mins!+60
    set /a hrs=!hrs!-1
)
if %hrs% lss 0 (
    set /a hrs=!hrs!+24
)
set /a tot=%secs%+%mins%*60+%hrs%*3600

echo End     = %endtime%
echo Start   = %starttime%
echo Hours   = %hrs%
echo Minutes = %mins%
echo Seconds = %secs%
echo Total   = %tot%

rem ##########
rem Email LOGS
rem ##########

c:\blat\blat.exe -to %mail-to% -i %srvname% -s "%mail-subject%" -body "%mail-body%|Backup Report:|Start   = %starttime%|End     = %endtime%|Hours   = %hrs%|Minutes = %mins%||%footer%" -attach %attachment%

endlocal

rem ## THE END
rem ## Syed Jahanzaib / aacable@hotmail.com

 


 

To delete files olde then X days using FORFILES

 

forfiles /p “C:\test” /s /m *.* /c “cmd /c del @path” /d -15

 

Change /d -15 to match your requirements. you can change the del command to any other like to show the files, use echo. FORFILES is builtin command with Windwos 2003 /7. You can download it from http://www.ipass.net/davesisk/forfiles.zip


 Delete Files Over 15 Days Old using ROBOCOPY

set _robodel=%TEMP%\~robodel MD %_robodel% ROBOCOPY “C:\source_folder” %_robodel% /move /minage:15 del %_robodel% /q


Batch File to create Windows MS SQL Backup

First create .sql file that can be called from batch file to create any specific DB backup. for example c:\zaibdb.sql

BACKUP DATABASE [Promo] TO  DISK = N'D:\DataBaseBackup\zaibdb.Bak' WITH NOFORMAT, INIT,  NAME = N'Promo-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

now create a batch file which will call the above .sql file to start backup. for example c:\start_backup.bat

@echo off
echo Creating FULL backup in D:\zaibdb.back
echo %Date% >> D:\DataBaseBackup\zaibdb.txt
sqlcmd -S .\SQLEXPRESS -i c:\zaibdb.sql > D:\DataBaseBackup\zaibdb.txt
echo.
echo Done
rem ping 127.0.0.1 -n 10 > null
echo . >> D:\DataBaseBackup\zaibdb.txt
echo This backup set was last created at %Date%  >> D:\DataBaseBackup\zaibdb.txt
echo.

 


Another Backup script that map remote  server folder locally
and then copy the required files and then delete the files older then 20 days with email alert

UPDATED: 8-DEC-2017

@echo off
cls
echo This script is designed by Syed Jahanzaib / COMPANY IS Dept.
echo This script will copy some data to file server
echo.
rem # Syed Jahanzaib #
rem #######################################################
rem Setting various Descriptions via environment variables
rem #######################################################
setlocal enableextensions enabledelayedexpansion
set starttime=%time%
set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%
set srvname=MYSERVER.LOCAL
set description=myserver_db_backup_log_in_mail
set mail-subject=MYSERVER.LOCAL - Daily Status of myserver DB Backup Copied in folder \\fileserver\datapark\myserver
set mail-body=myserver DB Files which are copied from the c:\backup to File Server ......
set mail-to="AACABLEATHOTMAILDOTCOM"

set footer="Automated_COMPANY_myserver_START_SCRIPT_Created_by_Syed_Jahanzaib_COMPANY_(Pvt)_Ltd.IS_Dept."
set attachment=c:\scripts\myserverdb.log
taskkill /f /t /im "sed.exe" > null
del c:\backup\COMPNAME.txt > null
del c:\backup\ip.txt > null
del c:\backup\damwipfile.txt > null
echo. > %attachment%
echo. >> %attachment%

rem #########################
rem STart END Time Algorithm
rem #########################

set endtime=%time%
set total="echo Total = %tot%"

set /a hrs=%endtime:~0,2%
set /a hrs=%hrs%-%starttime:~0,2%

set /a mins=%endtime:~3,2%
set /a mins=%mins%-%starttime:~3,2%

set /a secs=%endtime:~6,2%
set /a secs=%secs%-%starttime:~6,2%

if %secs% lss 0 (
set /a secs=!secs!+60
set /a mins=!mins!-1
)
if %mins% lss 0 (
set /a mins=!mins!+60
set /a hrs=!hrs!-1
)
if %hrs% lss 0 (
set /a hrs=!hrs!+24
)
set /a tot=%secs%+%mins%*60+%hrs%*3600

echo End = %endtime%
echo Start = %starttime%
echo Hours = %hrs%
echo Minutes = %mins%
echo Seconds = %secs%
echo Total = %tot%

rem listing file for mail attention
echo This script will copy last date added files from c:\backup to to File server \\fileserver\datapark\myserver folder > %attachment%
echo Automated COMPANY myserver EXPORT SCRIPT ***** Created by Syed Jahanzaib_COMPANY (Pvt) Ltd.IS_Dept.
echo ************************************************************* >> %attachment%
echo Found Following File in c:\backup folder for copying to \\fileserver\datapark\myserver >> %attachment%

FORFILES /P C:\backup /M *.* /D -0 /C "CMD /C ECHO @FDATE @PATH - Size @FSIZE bytes - Modified Date @FDATE - Modified Time @FTIME" >> %attachment%
echo. >> %attachment%
echo ***** NOW Comparing above files with \\fileserver\datapark\myserver folder for verification >> %attachment%
echo. >> %attachment%

rem #########################
rem STart BACKUP
rem #########################

echo Executing Scripts Functions Now ... mapping network drive
net use T: \\fileserver\datapark\myserver

rem # Copying Last Date Export files to \\fileserver\export folder
FORFILES /P C:\backup /M *.* /D -0 /C "CMD /C copy @path T:\"

FORFILES /P "T:" /M *.* /D -0 /C "CMD /C ECHO @FDATE @PATH - Size @FSIZE bytes - Modified Date @FDATE - Modified Time @FTIME" >> %attachment%
echo ************************************************************* >> %attachment%
ping -n 2 127.0.0.1 > c:\nul

rem # Deleteing myserver DB files older then 15 Days from myserver server & file server as well. . .
echo Deleting files in c:\backup and file server path older then 15 days
FORFILES /P C:\backup /M *.* /D -15 /C "cmd /c del @path"
FORFILES /P "T:" /M *.* /D -15 /C "cmd /c del @path"

echo. >> %attachment%
echo *** Files Older then 15 days from myserver and File Server (if any matched) have been deleted. verify it. >> %attachment%

echo. >> %attachment%
echo. >> %attachment%
echo %footer% >> %attachment%

rem ##########
rem Email LOGS - YOU SHOULD HAVE BLAT installed
rem ##########

rem c:\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "%mail-subject%" -body "%mail-body%| %attachment% Backup Report:|Start = %starttime%|End = %endtime%|Hours = %hrs%|Minutes = %mins%||%footer%"
c:\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "%mail-subject%"
endlocal

rem ## THE END
rem ## Syed Jahanzaib / COMPANY (Pvt) Ltd. / IS Dept.

sample backup log.JPG

 


 

Daily Backup of Required Folder using ROBOCOPY

Robocopy method which will copy only new file by matching source and destination folder/file timstamps. Its much better as it displays results in command prompt with percentage and all the necessary info any admin want. ūüôā its my favorite. You can downlod Robocopy by downloading Microsoft Resource Kit from following link.
http://www.microsoft.com/en-us/download/details.aspx?id=17657

@echo off
Robocopy /E /LOG:h:\Softwares\Servers_Related\mail-backup-log.txt B:\archive\.  T:\backup\archive
Robocopy /E /LOG+:h:\Softwares\Servers_Related\mail-backup-log.txt T:\mailserver\c$\mt\.  T:\backup\mt
Robocopy /E /LOG+:h:\Softwares\Servers_Related\mail-backup-log.txt T:\mailserver\mail\.  T:\backup\mail

Second Version of robocopy which add logs, and emails too


@echo off
rem # Syed Jahanzaib #
rem #######################################################
rem Setting various Descriptions via environment variables
rem #######################################################

setlocal enableextensions enabledelayedexpansion
set starttime=%time%
set srvname=FILE_SERVER
set description=Target_Server - Daily Status of MAIL Server Data Copied in FILE_SERVER
set jobname=Target_Server - Daily Status of MAIL Server Data Copied in FILE_SERVER
set attachment=c:\backup\mail_backup_log.txt
set mail-subject=Target_Server - Daily Status of MAIL Server Data Copied in FILE_SERVER
set mail-body=Target_Server - Daily Status of MAIL Server Data Copied in FILE_SERVER
set mail-to=aacable@hotmail.com
set footer=Automated Backup and Email Logs Script Created by  / Syed Jahanzaib

rem Delete old mail backup log file
del c:\backup\mail_backup_log.txt
rem oNLY Mail NSF files Backup
Robocopy.exe *.nsf /w:0 /r:0 /LOG:c:\backup\mail_backup_log.txt /NP /FP /TEE /ts  \\Target_Server\d$\lotus\domino\data\mail H:\Target_Server\Target_Server_LIVE_DATA\MAIL

rem Mail Tracking Backup
Robocopy.exe *.nsf  /w:0 /r:0 /LOG+:c:\backup\mail_backup_log.txt /NP /FP /ts /TEE \\Target_Server\c$\mt\ H:\Target_Server\Target_Server_LIVE_DATA\Target_Server-MT

rem Transaction Logs for mail server
Robocopy.exe *.txn /w:0 /r:0 /LOG+:c:\backup\mail_backup_log.txt /NP /FP /TEE /ts \\Target_Server\c$\logdir\. H:\Target_Server\Target_Server_LIVE_DATA\LOGDIR

set endtime=%time%
set total="echo Total   = %tot%"

set /a hrs=%endtime:~0,2%
set /a hrs=%hrs%-%starttime:~0,2%

set /a mins=%endtime:~3,2%
set /a mins=%mins%-%starttime:~3,2%

set /a secs=%endtime:~6,2%
set /a secs=%secs%-%starttime:~6,2%

if %secs% lss 0 (
set /a secs=!secs!+60
set /a mins=!mins!-1
)
if %mins% lss 0 (
set /a mins=!mins!+60
set /a hrs=!hrs!-1
)
if %hrs% lss 0 (
set /a hrs=!hrs!+24
)
set /a tot=%secs%+%mins%*60+%hrs%*3600

echo End     = %endtime%
echo Start   = %starttime%
echo Hours   = %hrs%
echo Minutes = %mins%
echo Seconds = %secs%
echo Total   = %tot%

rem ##########
rem Email LOGS
rem ##########

c:\backup\blat\blat.exe -to %mail-to%  -attach %attachment% -i %srvname% -s "%mail-subject%" -body "%mail-body%|Backup Report:|Start   = %starttime%|End     = %endtime%|Hours   = %hrs%|Minutes = %mins%||%footer%"

endlocal

rem ## THE END
rem ## Syed Jahanzaib / aacable@hotmail.com

The above commands description is as follows.
/E  = Copy sub-directories, including Empty ones
/LOG+ = Output status to LOG file (append to existing log, so previous entries along with new one should be saved together, if you don’t use + , it will overwrite existing log-file, means delete old entries and overwrite new one)).


 

XCOPY Method

Following file will copy all the data from the source folder to target folder using windows builtin copy tool XCOPY.

@echo off

echo * * *  >> C:\backup-log.txt
echo Mail Backup Starts at %date% - %time%  >> C:\backup-log.txt

C:\windows\system32\xcopy.exe B:\source-folder\*.*  T:\targetfolder /S /D /C /Y

echo Mail Backup Ends at %date% - %time%  >> C:\backup-log.txt
echo * * * >> C:\backup-log.txt 

The above commands description is as follows.

/S = Copies directories and sub-directories except empty ones.
/D =  If no date is given, copies only those files whose  source time is newer than the destination time.
/C = Continues copying even if errors occur.
/Y  = Overwrite existing files if any without prompting, its necessary when you are running xcopy via batch / script file.

‚Ėľ


 

NET USE SHARING by COMMAND

net use B: \\server\datafolder /USER:administrator@mydomain password
net use B: \\server\datafolder /USER:pc-name\administrator password

 


Set Windows 7/x IP address via COMMAND / CLI

@echo off
echo.
echo Setting IP Address to AUTO DHCP [Office DHCP Server]...
echo.
netsh interface ip set address name="Local Area Connection" source=dhcp
netsh interface ip set address name="Wireless Network Connection" source=dhcp
echo.
echo.
echo Done....
echo.
pause

Another script to move files from one folder and delete directories older then XX DAys, I used it for group company.

@echo off
rem ################################
rem Move all folders from following from D:\1st_folder\ to D:\2nd_folder
robocopy D:\1st_folder\ D:\2nd_folder /s /e /MOVE
if not exist "D:\1st_folder\" mkdir D:\2nd_folder\

rem ################################
rem Delete folders older then 2 days

setlocal

set target=D:\2nd_folder
set days=-2

for /f "usebackq delims=" %%G in (
`forfiles /p "%target%" /c "cmd /c if /i @isdir == true echo @path" /d %days% 2^>nul`
) do rd /s /q "%%~G"

endlocal & exit /b

QUERY FILES BIGGER THAN 10 GB ON REMOTE SERVER FOLDER AND MAKE REPORT FOR EMAIL

@echo off
cls
set srvname=MYCOMPANY_Mail_Server
set description=Lotus Email Server Weekly Report - Users mail box size with 10GB or above usage
set jobname=Lotus Email Server Weekly Report - Users mail box size with 10GB or above usage
set attachment=c:\backup\emailusers10gbusage.log
set tmpfile=c:\backup\emailusers10gbusage_temp.log
set mail-subject=Lotus Email Server Weekly Report - Users mail box size with 10GB or above usage
set mail-body=Lotus Email Server Weekly Report - Users mail box size with 10GB or above usage
set mail-to=zaib@zaib.com
set footer=Lotus Email Server Weekly Report - Users mail box size with 10GB or above usage - Powered by ABC IS Dept.

echo Lotus Email Server Weekly Report - Users mail box size with 10GB or above usage > %attachment%
echo. >> %attachment%

powershell.exe -inputformat none -command "Get-ChildItem -Path \\MAILSRV01\lotus\Domino\data\mail | Where-Object {$_.length -gt 10GB} | Sort-Object -descending -Property length | Format-Table Name,FileSize" > %tmpfile%

echo INBOX Mail File Total Count: >> %attachment%
find /C "nsf" > %attachment%
type %tmpfile% >> %attachment%
powershell.exe -inputformat none -command "Get-ChildItem -Path \\MAILSRV01\archive | Where-Object {$_.length -gt 10GB} | Sort-Object -descending -Property Length | Format-Table Name,FileSize" > %tmpfile%

echo ARCHIVE Mail File Total Count: >> %attachment%
find /C "nsf" > %attachment%
type %tmpfile% >> %attachment%

echo This report is generated on %date% - %time% >> %attachment%
echo Powershell Script Powered by ABC IT Dept. >> %attachment%

rem ##########
rem Email LOGS
rem ##########

c:\backup\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "%mail-subject%"
rem notepad %attachment%
rem ## THE END
rem ## Syed Jahanzaib / ABC (Pvt) Ltd. / IT Dept.

QUERY Domain Users who have not logged in last 30 days & send email


@echo off
cls
set srvname=MYDCSRV01
set description=Domain Controller MYDCSRV01 Weekly Report - Users list who have not logged in last 30 days
set jobname=Domain Controller MYDCSRV01 Weekly Report - Users list who have not logged in last 30 days
set attachment=c:\backup\usersnotloggedlist.log
set tmpfile=c:\backup\usersnotloggedlist_temp.log
set mail-subject=Domain Controller MYDCSRV01 Weekly Report - Users list who have not logged in last 30 days
set mail-body=Domain Controller MYDCSRV01 Weekly Report - Users list who have not logged in last 30 days
set mail-to=zaib@zaib.zzz
set footer=Domain Controller MYDCSRV01 Weekly Report - Users list who have not logged in last 30 days - Powered by abc IS Dept.

echo Domain Controller MYDCSRV01 Weekly Report - Users list who have not logged in last 30 days > %attachment%
echo. >> %attachment%
powershell.exe -inputformat none -command "$DaysInactive = 30; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate,Description" > %tmpfile%

echo Total Count: >> %attachment%
find /C "UserPrincipalName" > %attachment%
echo. >> %attachment%

powershell.exe -inputformat none -command "$DaysInactive = 30; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate,Description" >> %attachment%

echo Powershell Script Powered by abc IS Dept. >> %attachment%

rem ##########
rem Email LOGS
rem ##########

c:\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "%mail-subject%"

rem ## THE END
rem ## Syed Jahanzaib / abc (Pvt) Ltd. / IS Dept.

Regard’s
Syed Jahanzaib

%d bloggers like this: