Robocopy script to transfer user data from old PC to new PC - batch-file

I am trying to write a script that I can use to remotely transfer data from an end user's computer, to a new one I am preparing for them. I will need to transfer data from multiple user profiles, so I have written it to cycle through the user profiles on the old machine, but I am unsure of the correct syntax in a couple places, specifically what variable I need to reference the current user folder as the script cycles through them (see the question marks in the directories listed below).
I wrote it to only copy user profiles that have been used in the last 90 days. I would like to copy a few profiles such as Public, Default, etc regardless of age, but I will probably just add a few more Robocopy lines to accomplish that.
Can anyone advise me on what the syntax needs to be where the question marks appear below? This would be $_ in Powershell, but I'm not sure what it is in a CMD batch file.
Thanks in advance,
Andrew
#echo off
Set /p OldPC=Please enter the old PC name:
Set /p NewPC=Please enter the new PC name:
for /D %%D in ("\\%OldPC%\USERS\*") do (robocopy "\\%OldPC%\USERS\?\Desktop" "\\%NewPC%\Users\?\Desktop" /E /Z /W:10 /COPYALL /MAXAGE:90
for /D %%D in ("\\%OldPC%\USERS\*") do (robocopy "\\%OldPC%\USERS\?\Documents" "\\%NewPC%\Users\?\Documents" /E /Z /W:10 /COPYALL /MAXAGE:90
for /D %%D in ("\\%OldPC%\USERS\*") do (robocopy "\\%OldPC%\USERS\?\Favorites" "\\%NewPC%\Users\?\Favorites" /E /Z /W:10 /COPYALL /MAXAGE:90
for /D %%D in ("\\%OldPC%\USERS\*") do (robocopy "\\%OldPC%\USERS\?\Pictures" "\\%NewPC%\Users\?\Pictures" /E /Z /W:10 /COPYALL /MAXAGE:90

I guess you needed more than what you asked.
From what I understood, you want to copy user profile folders for the users who have been using the computer since some date.
To solve the problem, it would be better to find users who logged on rather than finding any file that is edited. Finding edited files will consume too much time to just find the names of used user accounts.
Since there is wevtutil command that is used to deal with logged events, the code became quite simpler.
So the code looks like this:
#echo off
pushd %~dp0
setlocal EnableDelayedExpansion
::User Input
set /p OldPC=Please enter the old PC name:
set /p NewPC=Please enter the new PC name:
set /p UserName=Please enter the User name to use in %OldPC%:
set /p Password=Please enter the password to use in %OldPC%:
set /p MaxDate=Please enter the Maximum logon date:
cls
echo Deriving User Names that are used since %MaxDate%...
echo If this step takes too long, check if you typed correct user name and password.
wevtutil qe Security /r:%OldPC% /u:%UserName% /p:%Password% /f:text /q:"*[System[TimeCreated[#SystemTime>='%MaxDate%T00:00:00'] and (EventID=4624)]]" |^
findstr /b /c:" Account Name" >PossibleUserName.tmp1
dir /b "\\%OldPC%\Users" >UserProfileList.tmp1
findstr /g:"UserProfileList.tmp1" "PossibleUserName.tmp1"|sort >UserList.tmp2
del /q *.tmp1
cls
echo Formatting User List...
for /f "tokens=2 delims=: " %%a in (UserList.tmp2) do (
if not "!ln!"=="%%a" (
set "ln=%%a"
echo %%a>>FinalList.tmp
)
)
del /q *.tmp2
cls
echo Copying Files...
for /f "tokens=*" %%a in (FinalList.tmp) do (
echo robocopy "\\%OldPC%\Users\%%a\Desktop" "\\%NewPC%\Users\%%a\Desktop" /e /z /w:10 /copyall
echo robocopy "\\%OldPC%\Users\%%a\Documents" "\\%NewPC%\Users\%%a\Documents" /e /z /w:10 /copyall
echo robocopy "\\%OldPC%\Users\%%a\Favorites" "\\%NewPC%\Users\%%a\Favorites" /e /z /w:10 /copyall
echo robocopy "\\%OldPC%\Users\%%a\Pictures" "\\%NewPC%\Users\%%a\Pictures" /e /z /w:10 /copyall
)
echo Done!
del /q *.tmp
pause>nul
exit
Since you are trying to use the script from the remote computer, wevtutil command required log in information for your old PC.
Also, you need to input the date that you want to use in %MaxDate%, which will enable you to filter the logs since that date.
The date format should look like this: YYYY-MM-DD
For example, you should type 2017-01-01 if you want to filter users who used the computer since January 1, 2017.
If you set both old and new computers to share their Users Directories with correct properties, then you would be good to go with this code.
I hope this code would solve your problem.

Related

Batch File to Remove Files from C:\Users folder

I work in a domain environment where devices store local user profiles in the C:\Users folder.
I would like to develop a batch files for users to be able to run to remove files (user profiles) that have not been modified in 90 days. I do need an exemption for any file that ends in .OA or .SA
I had this, but it was started to look in C:\Users\All Users however, that is not one of the directories available to delete.
ForFiles /p "C:\Users" /s /d -90 /c "cmd /c del #file"
Any assistance would be greatly appreciated.
I have decided to post this single line batch-file as a potential solution for isolating the active user accounts you wish. However I will add, that whilst I have used an improved version of your intended ForFiles command, I do not advise that you use it in a real environment. I say that because, depending upon the age of the user account, there will very likely be a great many files within those directory trees, which are needed. Just because a file has not modified, within a certain timespan, it does not mean that it can be deleted. For that reason I have used Echo #Path at the end of the command line, instead of your submitted Del #File. If you are happy to delete everything which is returned from my code above, feel free to make your deletion replacement.
#For /F Tokens^=2^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe UserAccount Where "AccountType = 512 And LocalAccount = 'TRUE' And SIDType = 1 And Status = 'OK'" Assoc:List /ResultClass:"Win32_SID" 2^>NUL ^| %SystemRoot%\System32\findstr.exe "__R"') Do #For /F Tokens^=6^ Delims^=^" %%H In ('%SystemRoot%\System32\wbem\WMIC.exe Path Win32_UserProfile Where "LocalPath Like '%SystemDrive%\\Users\\%%' And SID = '%%G' And Special = 'FALSE'" Get LocalPath /Format:"MOF" 2^>NUL') Do #%SystemRoot%\System32\forfiles.exe /P "%%H" /S /D -90 /C "%SystemRoot%\System32\cmd.exe /D /C \"If #IsDir == FALSE If /I Not #Ext == \"OA\" If /I Not #Ext == \"SA\" Echo #Path\""

How to copy an entire folder with current date/time in destination folder name?

I tried a lot of searching and working around, but I am unable to get around this sticky problem and hence requesting for help. Almost all the solutions talk about file rename, but I am looking for a folder copy and rename. (I am not a batch or cmd expert.)
I have a requirement as below where I have two directories:
Source: C:\temp\LR_Results\
Destination: C:\temp\HTML_Reports\
I have a folder with name HTML_Report inside source directory C:\temp\LR_Results\ which I want to copy to destination directory C:\temp\HTML_Reports\.
The requirement is that a timestamp should be added to the folder name HTML_Report on being copied to the destination C:\temp\HTML_Reports\ from the source C:\temp\LR_Results\.
So the resulting directory structure should look like:
C:\temp\HTML_Reports\HTML_Report_dd_mm_yyyy_hhmmss
The timestamp should be the current date/time.
How can this be done with a batch file?
The following code can be used to get current date and time in format dd_MM_yyyy_hhmmss without depending on which country is configured for the account used to run the batch file:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if exist %SystemRoot%\System32\robocopy.exe for /F "tokens=1-6 delims=/: " %%I in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do set "CurrentDateTime=%%K_%%J_%%I_%%L%%M%%N" & goto CopyDirectory
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "CurrentDateTime=%%I"
set "CurrentDateTime=%CurrentDateTime:~6,2%_%CurrentDateTime:~4,2%_%CurrentDateTime:~0,4%_%CurrentDateTime:~8,6%"
:CopyDirectory
%SystemRoot%\System32\xcopy.exe "C:\temp\LR_Results\HTML_Report" "C:\temp\HTML_Reports\HTML_Report_%CurrentDateTime%\" /C /E /H /I /K /Q /R /Y >nul
endlocal
The code uses ROBOCOPY to get current date time region independent on being available which is the case by default for Windows Vista and Windows Server 2003 and all later Windows versions. The much slower solution with WMIC is used on Windows XP on which ROBOCOPY is not available by default.
For a detailed explanation of the three command lines used to get the current date and time region independent with either ROBOCOPY or WMIC read my answer on Time is set incorrectly after midnight.
See also my answer on single line with multiple commands using Windows batch file for an explanation of operator & which is used to run command GOTO immediately after definition of environment variable CurrentDateTime as a result of processing the first line output by ROBOCOPY with date and time resulting in exiting the loop before processing the next line.
It would be much better to use as date/time format yyyy-MM-dd_hhmmss which is the international date format. It has the big advantage that multiple subdirectories in C:\temp\HTML_Reports with name HTML_Reports_yyyy-MM-dd_hhmmss displayed sorted alphabetically by name are at the same time also displayed sorted in chronological order. That really helps to get a better overview on the directories with the HTML reports.
The code necessary for date/time format yyyy-MM-dd_hhmmss with not writing as much as possible on a single command line for most efficient execution:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if exist %SystemRoot%\System32\robocopy.exe (
for /F "tokens=1-6 delims=/: " %%I in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do (
%SystemRoot%\System32\robocopy.exe "C:\temp\LR_Results\HTML_Report" "C:\temp\HTML_Reports\HTML_Report_%%I-%%J-%%K_%%L%%M%%N" /E /R:3 /W:2 /NDL /NFL /NJH /NJS
goto EndBatch
)
)
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "CurrentDateTime=%%I"
set "CurrentDateTime=%CurrentDateTime:~0,4%-%CurrentDateTime:~4,2%-%CurrentDateTime:~6,2%_%CurrentDateTime:~8,6%"
%SystemRoot%\System32\xcopy.exe "C:\temp\LR_Results\HTML_Report" "C:\temp\HTML_Reports\HTML_Report_%CurrentDateTime%\" /C /E /H /I /K /Q /R /Y >nul
:EndBatch
endlocal
This batch file uses ROBOCOPY to get region independent the current date and time and to copy the directory on being available. Otherwise WMIC is used to get region independent the current date and time and XCOPY is used to copy the directory.
The entire task can be done with a batch file containing just one command line on no compatibility with Windows XP must be taken into account and assuming that the required command extensions are enabled and not required delayed environment variable expansion is disabled as by default:
#for /F "tokens=1-6 delims=/: " %%I in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do #%SystemRoot%\System32\robocopy.exe "C:\temp\LR_Results\HTML_Report" "C:\temp\HTML_Reports\HTML_Report_%%I-%%J-%%K_%%L%%M%%N" /E /R:3 /W:2 /NDL /NFL /NJH /NJS & goto :EOF
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
goto /?
if /?
robocopy /?
set /?
setlocal /?
wmic /?
wmic os /?
wmic os get /?
wmic os get localdatetime /?
xcopy /?
I am sharing date formatting mechanism below. This will definitely help you create your solution.
set foldername=folder1
echo %foldername%_%date:~-4,4%%date:~-7,2%%date:~-10,2%%time:~0,2%%time:~3,2%
For further reading on Batch Scripting Refer its documentation or any tutorial such as this.
So the solution that worked for me is as below.
Yes, it only has rename command with the current date time stamp. to copy the folder, I used the inbuild commandline interface solution that comes with Team City Server, and then I made a call to the rename.bat file which did the trick for me.
Below is the rename Code:
#echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
CD C:\temp\HTML_Results
Rename HTML_Report HTML_Report_%mydate%_%mytime%
Definitely not the most efficient but works for me.

deleting files on multiple PC's with multiple users with batch file

I am trying to set up a batch program that will go to the different computers on my network (from .txt file) and then delete files from the users on the that PC, and then empty the recycle bin. I've got the second part working so I can delete files from multiple users on a PC, but I can't get it to look at other PC's. I was hoping someone might point out what I'm missing here. Here is what I have so far:
#ECHO off
Setlocal EnableDelayedExpansion
FOR /F "delims=" %%i IN (test.txt) DO (
for /f %%a in ('dir /B /AD C:\Users') do (
REM for /f "tokens=*" %%a in (userlist.txt) do (
if exist "C:\Users\%%a\" del /S /Q "C:\Users\%%a\AppData\Local\Lotus\Notes\Data\workspace\logs"
if exist "C:\Users\%%a\" del /S /Q "C:\Users\%%a\AppData\Local\Google\Chrome\User Data\Default\*"
if exist "C:\Users\%%a\" del /S /Q "C:\Users\%%a\AppData\Local\Microsoft\Windows\Temporary Internet Files"
)
RD %systemdrive%\$Recycle.Bin /S /Q
)
pause
Anybody got any pointers?
You need to use UNC paths.
\\server\sharename\folder\file.ext
You can get a list of computers with
for /f "skip=3" %A in ('net view ^| findstr /C:"\\"') do Echo %A
All computers have a share for admins only called C$ that is the C drive (and D$ etc). $ makes it hidden. So
for the local computer via UNC
del /S /Q "\\127.0.0.1\C$\User\username\AppData\Local\Lotus\Notes\Data\workspace\logs"
Also there is no point to If Exist, just delete it - it will work or not. If you care if it worked or not you test the return value If errorlevel 1 echo error. You are causing extra disk access and network traffic. In programming we do and test not test and do.
You can also run a batch on the other computer.
wmic /node:"#Computerlist.txt" process call create "c:\\batchfile.bat"
Note \\ in paths. C:\\batcfile.bat is C: on the remote computer. This allows you to only use one for loop in your batchfile. You copy the batch file with copy. Net View can generate the computer list although you have to remove \\
for /f "tokens=1 delims=\" %A in ('net view ^| findstr /C:"\\"') do Echo %A

Bat Error "invalid number of parameters"

I am trying to write a bat file to backup a folder on my work server (sometimes the server and backup server do not sync correctly and files go missing).
I have tried many different solutions and read a few different forums to try to resolve this, but I cannot seem to find anything.
#echo This will now create a new backup of S:\Internal Auditor\9 - September 14
#echo off
:: variables
set SRCFOLDER="S:\Internal Auditor\9 - September 14"
set DESTFOLDER="S:\Internal Auditor\2014\9 - Sept Backup"
set folder=%date:~5,2%-%date:~8,2%-%date:~0,4%
set backupcmd=xcopy /W /E /H /V /C /Z /I /F /J /R /Y
echo ######## PLEASE WAIT SYSTEM BACKINGUP SOME DATA########
xcopy %SRCFOLDER% %DESTFOLDER% %backupcmd%
echo !!!!!!!!BACKUP COMPLETED THANKS!!!!!!!!!!!!!!
#pause
Please help - I'm tired of losing files, and I don't want to have to manually backup files every day.
(The goal is the create a new folder with date & time every time it runs under the sub-folder "9 - September 14"{historical backup}).
EDIT
Ok - So I have another thread open for something that was different, but now my 2 questions have kinda merged together, so please look # New folder for every backup CMD and see if you could help...
use set backupcmd=/W /E /H /V /C /Z /I /F /J /R /Y
instead of set backupcmd=xcopy /W /E /H /V /C /Z /I /F /J /R /Y . You have redundant xcopy in parameters.
EDIT. As far as I understood your comments you need a new folder like this "S:\Internal Auditor\%date:~5,2%-%date:~8,2%-%date:~0,4%"
so you can do this:
set SRCFOLDER="S:\Internal Auditor"
set "DESTFOLDER="S:\Internal Auditor\2014"
set "folder=%date:~5,2%-%date:~8,2%-%date:~0,4%"
md "%DESTFOLDER%\%folder%" >nul 2>&1
set "backupcmd=/W /E /H /V /C /Z /I /F /J /R /Y"
echo ######## PLEASE WAIT SYSTEM BACKINGUP SOME DATA########
xcopy "%SRCFOLDER%\%folder%" "%DESTFOLDER%\%folder%" %backupcmd%
echo !!!!!!!!BACKUP COMPLETED THANKS!!!!!!!!!!!!!!
After you enter the required source and destination path try this code..
set xcopy=xcopy //switches as per your requirement
set Folder=%Date:~-7,2%-%Date:~-10,2%-%Date:~-4,4%
mkdir %DESTPATH%\%Folder%
pause
%xcopy% %SOURCEPATH% %DESTPATH%\%Folder%
pause

looping the CACLS function in batch

I would like to lock a series of file from my staff so they can not delete them i have thus compiled a script wich puts the CACLS function into a loop. however this is not taking effect.
could somebody please explain why?
FOR /F %%i IN (c:\file.txt) DO CACLS %%i /p :n /y
I have been able to narrow it down to the /y at the end how can i continue to Automate the yes?
There are a couple of things wrong.
Firstly you haven't specified a user/group that you want to apply the permissions to
Example
CACLS %%i /p Everyone:n /y
Secondly, there is no /y switch for cacls. If you want to automatically say y to the confirmation you can use this
echo y| CACLS %%i /p Everyone:n /y
So your full batch file would look similar to this
FOR /F %%i IN (c:\file.txt) DO echo y| CACLS %%i /p Everyone:n
Hope this helps

Resources