Batch path variable does not work in Windows Server 2016 - batch-file

we recently switched from Windows Server 2008 to 2016 and we have some tasks to delete files and folders based on batch every day.
Here is the code:
set successful="D:\TEST\logs\successful.log"
set failed="D:\TEST\logs\failed.log"
set delpath="D:\TEST\1 und 2"
echo Logged time = %time% %date% >> %successful%
echo Logged time = %time% %date% >> %failed%
echo Files deleted: >> %successful%
echo Files failed to delete: >> %failed%
forfiles -p %delpath% -m *.* -c "cmd /c del /q #path && echo #path>>%successful% || echo #path>>%failed%"
forfiles -p %delpath% -c "cmd /c IF #isdir == TRUE rd /S /Q #path && echo #path>>%successful% || echo #path>>%failed%"
echo. >> %successful%
echo. >> %failed%
Since server 2016 this batch does not work.
Some issue with spaces in the path.
Output is:
ERROR: Invalid argument/option - 'und'.
Type "FORFILES /?" for usage.
Could there be some changes in syntax of the path? Did I miss quotation marks?

Here's a quick example of what I understand to be the same task, (emptying "D:\TEST\1 und 2" and logging both failed and successful actions); but using For loops instead of ForFiles commands. Please feel free to give it a try and report back as necessary.
#Echo Off
Set "successful=D:\TEST\logs\successful.log"
Set "failed=D:\TEST\logs\failed.log"
Set "delpath=D:\TEST\1 und 2"
(Echo Logged time = %TIME% %DATE%&Echo Files deleted:)>>"%successful%"
(Echo Logged time = %TIME% %DATE%&Echo Files failed to delete:)>>"%failed%"
For /D %%A In ("%delpath%\*")Do RD /S/Q "%%A" 2>Nul&&(>>"%successful%" Echo %%A)||>>"%failed%" Echo %%A
For %%A In ("%delpath%\*")Do Del "%%A" 2>Nul&&(>>"%successful%" Echo %%A)||>>"%failed%" Echo %%A
Echo(>>"%successful%"
Echo(>>"%failed%"

The issue has nothing to do with the name of the directory itself, but more with the fact if the directory is empty or not, as you can see in following experiment (I started adding an empty file "blabla.txt" in the directory, and I deleted it afterwards):
Prompt>forfiles /P "C:\1 und 2" /C "cmd /c echo #path"
"C:\1 und 2\blabla.txt"
Prompt>del "1 und 2\blabla.txt"
Prompt>forfiles /P "C:\1 und 2" /C "cmd /c echo #path"
ERROR: The system cannot find the file specified.

Related

How to record purged files into a log file

I am using the following code in a batch file to purge any files older than 60 days. I would like the log file to print the file names that have been purged for record keeping purposes. How can I do that?
setlocal EnableDelayedExpansion
set logpath=C:\Temp\Archive
REM if not exist %logpath% md %logpath%
set FILEAGE=60
set archlog=%logpath%\Accurate_ARCHIVE.txt
set inputdir=C:\Temp
REM Set the date
FOR /f "tokens=2,3,4 delims=/ " %%a in ('date/t') do (set DD=%%a) & (set MM=%%b) & (set YYYY=%%c)
REM * Purge files older than %FILEAGE% days from disk.
forfiles /p "%inputdir%" /s /m *.* /d -%FILEAGE% /c "cmd /c del #path"
ECHO Folder %inputdir% was processed on %DD%-%MM%-%YYYY% >> %archlog%
ECHO Files older than %FILEAGE% days have been purged. >> %archlog%
exit %errorlevel%
I am expecting the log file to print the names of the files purged.
Add echo #path to the del #path command.
Something like below (untested).
"cmd /c (del #path) & (>> %archlog% echo #path)"
A more advanced version incorporating comments by Aschipf and Compo.
The 0x22 puts doupble quots around the filename and prevents problems with space and other special characters in the filename.
Deleted files are reported and files that could not be deleted are reported prefixed with NOT DELETED:.
"cmd /c if #isdir==FALSE (del #path) & (>> 0x22%archlog%0x22 if exist #path (echo NOT DELETED: #path) else (echo #path))"

batch file creates log file with incorrect log name

Batch file creates log file with incorrect log name.
I am running on Windows 10
There are two batch files.
Bat File 1 sets up some these variables and calls the 2nd batch file.
V_FILE_DIR, V_BAT_FILE_DIR, V_FILE_NAME, V_FILE_DAYS_OLD, V_LOG_FILE_NAME.
Bat File 2 accepts the environment variables sent by the Bat File 1.
and uses them to look for files in a directory that are greater than N days old.
It creates a log file with the number of files it is going to delete and a list of the files that will be deleted.
then it deletes the files.
These batch files work perfectly when I execute them from Windows Explorer.
When they are executed by Windows Scheduler they delete the files but the log file is given the incorrect log name and the deleted file are not listed inside the log file.
: ---- remove_MVIEW_SERVICE_BI_PART_MASTER_old_files.bat
: Bat file #1
#set V_FILE_DIR="C:\Users\khughes\Desktop\KCH_WAKA-PDMDB-V01_WINDCHILL_PROD\Oracle\0BAT\MVIEW_SERVICE_BI_PART_MASTER"
#set V_BAT_FILE_DIR="C:\Users\khughes\Desktop\KCH_WAKA-PDMDB-V01_WINDCHILL_PROD\Oracle\0BAT\REMOVE_OLD_FILES"
#SET V_FILE_NAME="*.LOG"
#SET V_FILE_DAYS_OLD=14
#SET V_LOG_FILE_NAME=MVW_SRVCE_BI_PRT_MSTR
call %V_BAT_FILE_DIR%\remove_old_files.bat %V_FILE_DIR% %V_BAT_FILE_DIR% %V_FILE_NAME% %V_FILE_DAYS_OLD% %V_LOG_FILE_NAME%
: Bat file #2
#IF [%1]==[] goto NOPARM
:---> Set variables section
#set V_FILE_DIR=%1%
#set V_BAT_FILE_DIR=%2%
#SET V_FILE_NAME=%3%
#SET V_FILE_DAYS_OLD=%4%
#SET V_LOG_FILE_NAME=%5%
#set V_HOUR=%time:~0,2%
#if "%V_HOUR:~0,1%" == " " set hour=0%V_HOUR:~1,1%
:echo hour=%V_HOUR%
#set V_MIN=%time:~3,2%
#if "%V_MIN:~0,1%" == " " set min=0%V_MIN:~1,1%
:echo min=%V_MIN%
#set V_SECS=%time:~6,2%
#if "%V_MIN:~0,1%" == " " set secs=0%V_MIN:~1,1%
:echo V_SECS=%V_MIN%
#set V_MONTH=%date:~-10,2%_%date:~-7,2%_%date:~-4,4%
#set V_YEAR=%date:~-4%
#set V_DATE_TIME=%V_MONTH%__%V_HOUR%_%V_MIN%_%V_SECS%
:---> Code section
#echo off
set "File=tmpfile"
set /a count=0
SETLOCAL enabledelayedexpansion
forfiles /p %V_FILE_DIR% /m %V_FILE_NAME% -d -%V_FILE_DAYS_OLD% /c "cmd /c echo The extension of #file is 0x09#ext") >> tmpfile
for /F "tokens=* delims=" %%a in ('Type "%File%"') do (
Set /a count+=1
Set "output[!count!]=%%a" )
IF %count% EQU 0 (Echo No files found to delete) ELSE (Echo %count% files were found to delete)
set V_NEWFILENAME=%V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo "--->*******************************************" >> %V_NEWFILENAME%
echo "--->* %count% files deleted on %V_DATE_TIME% *" >> %V_NEWFILENAME%
echo "--->*******************************************" >> %V_NEWFILENAME%
forfiles -p %V_FILE_DIR% -m %V_FILE_NAME% -d -%V_FILE_DAYS_OLD% -c "cmd /c echo del #path" >> %V_NEWFILENAME%
forfiles -p %V_FILE_DIR% -m %V_FILE_NAME% -d -%V_FILE_DAYS_OLD% -c "cmd /c del #path"
del %V_BAT_FILE_DIR%\tmpfile
goto exit1
:NOPARM
echo '******* Parameter Value Missing *******' >> V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
:exit1
echo . >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo '***********************' >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo '******* Exiting *******' >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo '***********************' >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
EXIT /b

Send files to a ftp server and then check if it was really sent using .bat

I was making a .bat code to send .txt files to a specific folder on my ftp server. But I also wanted a way to check if these files were really uploaded. I searched a lot on the internet and unfortunately, I realized that it can't be done using .bat command.
So I tried using another way: The .bat will send the files and then will take it back to the folder, if the file already exists in the folder it will show a message that the file was successfully uploaded.
I did this script below, but the part of the "checking if was uploaded" is not working right.
Someone can help me?
#echo off
#setlocal enableextensions
#cd /d "%~dp0"
mode 34,12
color 0a
Ping www.google.nl -n 1 -w 1000 >nul 2>nul
if errorlevel 1 (set internet=Nao foi possivel se conectar ao servidor) else (set internet=Conectado) >nul 2>nul
echo %internet%
if "%internet%"=="No connection" goto 1
if "%internet%"=="Conected" goto 2
:1
echo No connection
echo.
echo Try later...
echo.
pause
exit
:2
( echo open ftp.xxxxxxxxxxx.com
echo xxxxxxx
echo xxxxxxx
echo ascii
echo lcd "c:\Vendas Pay&Go\files"
echo cd "Vendas Cartões Pay&Go"
echo cd "ECO"
echo mput *.txt
echo bye
)> %temp%\ftpsend.dat
ftp -i -s:%temp%/ftpsend.dat >nul 2>nul
del /f /s /q %temp%\ftpsend.dat >nul 2>nul
( echo open ftp.xxxxxxx.com
echo xxxxxxx
echo xxxxxxx
echo ascii
echo lcd "c:\Vendas Pay&Go\files"
echo cd "Vendas Cartões Pay&Go"
echo cd "ECO"
echo mget *.txt
echo bye
)> %temp%\ftpsend.dat
ftp -i -s:%temp%/ftpsend2.dat >nul 2>nul
del /f /s /q %temp%\ftpsend2.dat >nul 2>nul
if %*.txt% exist goto3
:4
echo File was not uploaded
pause
:3
echo File Uploaded.
del /s /f /q "c:\Vendas Pay&Go\files\*.txt"
If you want to conditional execution to display a message you can do something like this. The && means the previous command was successful. The || means the previous command was not successful.
(ftp -i -s:%temp%/ftpsend.dat | find /I "file successfully transferred" >nul) && (echo File Successfully Transferred) || ( echo File not transferred. Tray again later.)
Updated version based on comment below
(ftp -i -s:%temp%/ftpsend.dat | find /I "file successfully transferred" >nul) && (
echo File successfully sent.
del /f /s /q "c:\Vendas Pay&Go\files\*.txt" >nul
) || (
cls
echo File not uploaded. Try later.
)

Using native Win 7 batch methods to remotely recreate a users profile?

I made a simple batch for XP that our team used to recreate XP profiles in a corporate environment but we have since moved to Win 7. Obviously recreating a User Profile in 7 is a little bit more complicated than simply renaming the old profile, dropping a Restore batch in the All Users startup folder and then letting Windows create a fresh profile on login. Writing a batch tends to get a little too complicated on the if/then/else statements for me, so I'm hoping to keep it simple like the old one. Someone suggested I incorporate a small command-line friendly user profile deletion utility into the batch, but I haven't found any that first offers a backup. Which means I'd have to Robocopy the entire user profile first, then restore all the data on login. I'm "hoping" to avoid that time investment. It also makes me a bit nervous relying on no errors during the copying process before being all deleted on the next step. Which is why I really like the renaming of user profiles in XP for worst case scenarios. Can anyone point me in the direction of either a simple utility that does this, or can throw some quick and easy code together I might be able to use? Most of my XP batch was just using c$ access, simple commands like
rename "\\%ip%\c$\Documents and Settings\%USERNAME%" %USERNAME%.%date%
All your help is greatly appreciated!
The path has changed in Win 7. It's now c:\users.
if exist c:\user rename "\\%ip%\c$\Users\%USERNAME%" "%USERNAME%.%newdate%"
if exist "c:\Documents and settings" rename "\\%ip%\c$\Documents and Settings\%USERNAME%" "%USERNAME%.%newdate%"
Also %date% will contain illegal characters .
Set newdate=%date:\=%
Will put the digits without seperators into newdate.
We utilize this in an Win 7 environment and does not have to be ran with elevated rights and can be done remotely. Key is the PC has be restarted and the user to not log in until after this script has run. After the user logs in and the script completes on the remote PC. You will have to remap any network printers and attach any PST files in Outlook.
#echo off
cls
title Profile Rebuilder (Local/Remote)
echo.
echo.
echo This batch file will rebuild a user's Windows 7 profile.
echo It is intended to help speed the process of rebuilding
echo a corrupted user profile either locally (while logged in
echo as DFASADMIN), or remotely. Either way the user who's
echo profile is being rebuilt can't be logged in and the PC
echo must have been rebooted.
echo.
echo.
set /p cont=Do you wish to continue with the profile rebuild (y/n):
if /i "%cont%"=="n" goto end
:local
echo.
set /p local=Is this script being run from a remote PC (y/n):
:rebooted
echo.
set /p reb=Has the PC been rebooted (y/n):
if /i "%reb%"=="y" goto renameremote
if /i "%local%"=="y" goto warn2
:warn1
cls
color c0
echo.
echo This script can not continue until the PC has been rebooted!
echo Please reboot now and then re-run this batch file.
echo.
pause
exit
:warn2
cls
color c0
echo.
echo This script can not continue until the PC has been rebooted!
echo Please have the user reboot now. Ensure they do not login.
echo.
pause
color 0f
goto rebooted
:renameremote
if /i "%local%"=="n" goto renamelocal
cls
echo.
echo.
set /p comp=Please enter the Computer Name or IP address of the remote PC:
echo.
echo Available Profiles:
dir /b "\\%comp%\c$\Users" | Find /v /i "users" | Find /v /i "default" | Find /v /i "dfasadmin" | Find /v /i "Public" | Find /v /i "runapps" | Find /v /i "mrbaInstall" | Find /v /i "test"
If Not %ErrorLevel%==0 goto Error
goto vername
:Error
cls
color c0
echo.
echo %comp% could not be contacted.
echo Please verify network connectivity and try again.
echo.
echo.
pause
exit
:vername
echo.
set /p name=Enter the profile name (i.e. firstname_lastname):
if /i not exist "\\%comp%\c$\Users\%name%" goto vername
if exist "\\%comp%\c$\Users\%name%.bak2" move "\\%comp%\c$\Users\%name%.bak2" "\\%comp%\c$\Users\%name%.bak3"
if exist "\\%comp%\c$\Users\%name%.bak" move "\\%comp%\c$\Users\%name%.bak" "\\%comp%\c$\Users\%name%.bak2"
move "\\%comp%\c$\Users\%name%" "\\%comp%\c$\Users\%name%.bak"
if /i not exist "\\%comp%\c$\Users\%name%.bak" goto failed
set drv=\\%comp%\c$
goto restore
:renamelocal
cls
echo.
echo Available Profiles:
dir /b "C:\Users" | Find /v /i "user" | Find /v /i "default" | Find /v /i "dfasadmin" | Find /v /i "helpdesk" | Find /v /i "runapps" | Find /v /i "mrbaInstall" | Find /v /i "test"
:vername2
echo.
set /p name=Enter the profile name (i.e. firstname_lastname):
if /i not exist "C:\Users\%name%" goto vername2
if exist "C:\Users\%name%.bak2" move "C:\Users\%name%.bak2" "C:\Users\%name%.bak3"
if exist "C:\Users\%name%.bak" move "C:\Users\%name%.bak" "C:\Users\%name%.bak2"
move "C:\Users\%name%" "C:\Users\%name%.bak"
if /i not exist "C:\Users\%name%.bak" goto failed
set drv=C:
:restore
echo #echo off >"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo cls >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo title Restoring Profile Data >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo **************************************************** >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo DO NOT CLOSE THIS WINDOW UNLESS INSTRUCTED TO DO SO. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo **************************************************** >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's Desktop... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\Desktop" "C:\Users\%name%\Desktop" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's Favorites... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\Favorites" "C:\Users\%name%\Favorites" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's Documents... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\Documents" "C:\Users\%name%\Documents" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\My Documents" "C:\Users\%name%\My Documents" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's Pictures... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\Pictures" "C:\Users\%name%\Pictures" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\My Pictures" "C:\Users\%name%\My Pictures" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's PST files... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo if not exist "C:\Users\%name%\Documents\Outlook Files" mkdir "C:\Users\%name%\Documents\Outlook Files"
echo if not exist "C:\Users\%name%\My Documents\Outlook Files" mkdir "C:\Users\%name%\My Documents\Outlook Files"
echo xcopy "C:\Users\%name%.bak\AppData\Local\Microsoft\Outlook\*.pst" "C:\Users\%name%\Documents\Outlook Files" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\AppData\Local\Microsoft\Outlook\*.pst" "C:\Users\%name%\My Documents\Outlook Files" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's Roaming Settings... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\AppData\Roaming\Microsoft\Signatures" "C:\Users\%name%\AppData\Microsoft\Signatures" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\AppData\Roaming\Microsoft\Proof" "C:\Users\%name%\AppData\Microsoft\Proof" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo if exist "C:\Users\%name%.bak\WinGamps32.ini" xcopy "C:\Users\%name%.bak\WinGamps32.ini" "C:\Users\%name%" /c /g /h /i /k /q /s /y >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\AppData\Roaming\Microsoft\Windows\Themes" "C:\Users\%name%\AppData\Roaming\Microsoft\Windows\Themes" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring The User's Local Settings... >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo xcopy "C:\Users\%name%.bak\AppData\Local\Microsoft\Windows\Themes" "C:\Users\%name%\AppData\Local\Microsoft\Windows\Themes" /c /g /h /i /k /q /s /y /exclude:C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo Restoring Printers
echo regedit /ADD \\%comp%\c$\Temp\Printers.reg
echo echo.
echo cd /d "C:\Users\%name%" >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo cls >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo The profile data has been restored. You still need to: >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo 1) Re-map printers. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo 2) Setup Outlook. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo 3) Login MS Communicator. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo 4) Manually delete C:\ProgramData\Microsoft\Windows\Start Menu >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat""
echo echo Start Menu\Programs\Startup\rebuild.bat (if present). >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo 5) Delete C:\Users\%name%.bak >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo when profile has been verified! >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo echo. >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo pause >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo attrib -h -r -s C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo del /q C:\rbexclude.txt >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo attrib -h -r -s "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat" >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo del /s /q "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat" >>"%drv%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\rebuild.bat"
echo .tmp >"%drv%\rbexclude.txt"
echo .err >>"%drv%\rbexclude.txt"
echo .ost >>"%drv%\rbexclude.txt"
echo .oab >>"%drv%\rbexclude.txt"
echo .mp3 >>"%drv%\rbexclude.txt"
echo .mp4 >>"%drv%\rbexclude.txt"
echo .wma >>"%drv%\rbexclude.txt"
echo extend.dat >>"%drv%\rbexclude.txt"
echo extend.dat _ActiveCACBAK >>"%drv%\rbexclude.txt"
goto regedit
:failed
cls
color c0
echo.
echo ********************** ERROR ***********************
echo.
echo The %name% profile could not be backed up.
echo Unable to rebuild this profile.
echo This script will now exit.
echo.
echo ****************************************************
echo.
echo.
pause
exit
:regedit
cls
:regedit /EXPORT \\%comp%\c$\Temp\Printers.reg "HKEY_CURRENT_USER\Printers"
COLOR 4F
echo.
echo *************** WARNING WARNING WARNING WARNING WARNING ***********************
echo.
echo Before continuing, You must now delete the profile registry and related
echo GUID keys. Run REGEDIT as administrator!
echo.
echo HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
echo.
echo and
echo.
echo HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileGuid
echo.
echo NOTE: There is not GUID for 64 Bit Windows.
echo.
echo *************** WARNING WARNING WARNING WARNING WARNING ***********************
echo.
pause
COLOR 07
goto complete
:complete
cls
echo.
echo.
echo Profile rebuild is now ready to run!
echo.
echo Please have the user login now. You will still need to:
echo 1) Manually re-map printers.
echo 2) Manually setup Outlook.
echo 3) Manually login MS Communicator if not signed in already.
echo 4) Manually delete C:\ProgramData\Microsoft\Windows\
echo Start Menu\Programs\Startup\rebuild.bat (if present).
echo 7) Manually delete C:\Users\%name%.bak
echo when profile has been verified.
echo.
pause
:end
I actually just went though the same thing!! Ok so the following "code" I threw together is in batch because it was easy and lightweight. It ain't pretty but it gets the job done.
Steps it does:
Connects to the machine and user profile. If the machine is offline, it will tell you. If the username provided doesn't match a profile, it will return a list of profiles on the computer so you can match the caller to the correct profile.
Backs up EFS Certificates to desktop.
Network drives and printers backed up to a text file on user's desktop.
User is automatically logged off
Appends 'old_' to the beginning of the local profile name and the date and time of rebuild to the end.
Backup of the profile registry key exported the old profile's 'Contacts' folder and then deletes it from the hive.
Copies a 'Profile Migration Tool' to the user's Desktop. This will move all the data from the old profile to the rebuilt one. It also copies the "Map all PST files.vbs" file found in Fix Pack. The "Map all PST files.vbs" file is automatically launched after all the data is migrated
After all steps are complete, Outlook launches
Step 1: You need to backup their data so here's that. Save it as Backup.bat
#title Profile Data Backup Tool v1.53
#echo off
echo.
echo.
if exist %USERPROFILE%\desktop\EFSCertBackup.cer del %USERPROFILE%\desktop\EFSCertBackup.cer
>goto :deletePFXFile
:deletePFXFile
if exist %USERPROFILE%\desktop\EFSCertBackup.pfx del %USERPROFILE%\desktop\EFSCertBackup.pfx
goto :backupefscerts
echo.
:backupefscerts
REM back up EFS Certs
echo This is a password you will create. If you do not want to create a password, press 'Enter' twice.
echo.
cipher /r:%USERPROFILE%\desktop\EFSCertBackup
REM back up network drives
net use > %USERPROFILE%\Desktop\NetworkDrivesandPrinters.txt
REM back up network printers
Cscript %WINDIR%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs -l >> %USERPROFILE%\Desktop\NetworkDrivesandPrinters.txt
REM backup the registry key
set THEME_REGKEY="HKLM\SOFTWARE\Wow6432Node\Network Associates\ePolicy Orchestrator\Agent"
set THEME_REGVAL=LoggedOnUser
REM Check for presence of key first.
reg query %THEME_REGKEY% /v %THEME_REGVAL% || (echo No theme name present! & pause & exit /b 1)
REM query the value. pipe it through findstr in order to find the matching line that has the value. only grab token 3 and the remainder of the line. %%b is what we are interested in here.
set THEME_NAME=
for /f "tokens=2,*" %%a in ('reg query %THEME_REGKEY% /v %THEME_REGVAL% ^| findstr %THEME_REGVAL%') do (
set THEME_NAME=%%b
)
REM replace any spaces with +
set THEME_NAME=%THEME_NAME: =+%
echo.
echo Please wait. This window will close automatically once the tool is done running.
echo Please inform the agent once this window closes.
wmic useraccount where (name='%THEME_NAME%') get sid >SID.txt
powershell -Command "(gc SID.txt) -replace 'SID', '' | Out-File SID.txt"
powershell -Command "(gc SID.txt) -replace ' ', '' | Out-File SID.txt"
powershell -Command "(gc SID.txt) | ? {$_.trim() -ne '' } | set-content SID.txt"
for /f "delims=" %%x in (SID.txt) do set SID=%%x
reg export "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%SID%" "%Userprofile%\contacts\oldprofileBackupKey.reg"
shutdown.exe /l /f
(goto) 2>nul & del "%~f0"
2. This will map any and all PST files the user has. Save it as "Map All PST Files.vbs"
On error resume next
Dim objFSO
Dim objWSH
Dim objWMIService
Dim colProcess
Dim objProcess
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWSH = CreateObject("Wscript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Dim strUserProfile
Dim OutlookOpen
strUserProfile = objWSH.ExpandEnvironmentStrings("%USERPROFILE%")
objWSH.Run "%COMSPEC% /c DIR " & CHR(34) & strUserProfile & "\*.pst" & CHR(34) & " /b /s>" & CHR(34) & strUserProfile & "\My Documents\PST Locations.txt""", 0, True
objWSH.Run "%COMSPEC% /c DIR H:\*.pst /b /s>>" & CHR(34) & strUserProfile & "\My Documents\PST Locations.txt""", 0, True
If Not objFSO.FileExists(strUserProfile & "\My Documents\PST Locations.txt") Then
Done()
End If
Dim AppOutlook, OutlookNS, Path, objfile, Line
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process")
For Each objProcess In colProcess
If objProcess.Name = "OUTLOOK.EXE" Then OutlookOpen = True
Next
Set AppOutlook = CreateObject("Outlook.Application")
If err.number <> 0 Then
Set AppOutlook = GetObject(,"Outlook.Application")
End If
Set OutlookNS = AppOutlook.GetNameSpace("MAPI")
Set objfile = objFSO.opentextfile(strUserProfile & "\My Documents\PST Locations.txt")
Do Until objfile.AtEndOfStream
Line=objfile.readline
If instr(Line, "No PST mappings found") Then
Done()
Else
OutlookNS.AddStore Line
End If
Loop
If Not OutlookOpen Then
AppOutlook.Session.Logoff
AppOutlook.Quit
End If
objfile.close
Set objfile = Nothing
Set AppOutlook = Nothing
Set OutlookNS = Nothing
Done()
Sub Done()
MSGBOX "Remapping of PST(s) is complete. Please ensure that your PST(s) have been remapped succesfully."
If Not OutlookOpen Then objWSH.Run "%COMSPEC% /c Start Outlook",0,False
objFSO.DeleteFile(strUserProfile & "\Desktop\Map All PST Files.vbs")
Wscript.Quit
End Sub
3. This is the part that will move all of their data from the old profile to the new one. Save it as "Profile Migration Tool.bat"
#echo off
set THEME_REGKEY="HKLM\SOFTWARE\Wow6432Node\Network Associates\ePolicy Orchestrator\Agent"
set THEME_REGVAL=LoggedOnUser
cls
REM Check for presence of key first.
reg query %THEME_REGKEY% /v %THEME_REGVAL% || (echo No theme name present! & pause & exit /b 1)
cls
REM query the value. pipe it through findstr in order to find the matching line that has the value. only grab token 3 and the remainder of the line. %%b is what we are interested in here.
set THEME_NAME=
for /f "tokens=2,*" %%a in ('reg query %THEME_REGKEY% /v %THEME_REGVAL% ^| findstr %THEME_REGVAL%') do (
set THEME_NAME=%%b
)
cls
set /p content=<oldprofile.txt
robocopy "%content%\Contacts" "C:\Users\%THEME_NAME%\Contacts" /MIR /E /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Downloads" "C:\Users\%THEME_NAME%\Downloads" /MIR /E /COPY:DAT /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Documents" "C:\Users\%THEME_NAME%\Documents" /MIR /E /COPY:DAT /IS /XA:SHT /XD "My Music" /XD "My Pictures" /XD "My Videos" /XF *.ini /R:2 /W:5
robocopy "%content%\Desktop" "C:\Users\%THEME_NAME%\Desktop" /MIR /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Favorites" "C:\Users\%THEME_NAME%\Favorites" /MIR /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Links" "C:\Users\%THEME_NAME%\Links" /MIR /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Music" "C:\Users\%THEME_NAME%\Music" /MIR /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Pictures" "C:\Users\%THEME_NAME%\Pictures" /MIR /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%\Videos" "C:\Users\%THEME_NAME%\Videos" /MIR /E /COPY:DAT /IS /XA:SHT /XF *.ini /R:2 /W:5
robocopy "%content%" "C:\Users\%THEME_NAME%\Documents" /COPY:DAT /IS /XD /XF ntuser.* /XF *.ini /R:2 /W:5
killtask /im outlook.exe
cd %currentuser%\Desktop
wscript "MAP ALL PST Files.vbs" //e:vbscript
del oldprofile.txt
del "%~f0"&exit
4. This is the holy grail. The part that actually rebuilds the profile. It does have to be run as an admin. Save it as RAP.bat:
#title Rebuild a Profile Tool Version 3.0
#echo off
:beginning
set THEME_REGKEY="HKLM\SOFTWARE\Wow6432Node\Network Associates\ePolicy Orchestrator\Agent"
set THEME_REGVAL=LoggedOnUser
REM Check for presence of key first.
reg query %THEME_REGKEY% /v %THEME_REGVAL% || (echo No theme name present! & pause>nul & exit /b 1)
REM query the value. pipe it through findstr in order to find the matching line that has the value. only grab token 3 and the remainder of the line. %%b is what we are interested in here.
set THEME_NAME=
for /f "tokens=2,*" %%a in ('reg query %THEME_REGKEY% /v %THEME_REGVAL% ^| findstr %THEME_REGVAL%') do (
set THEME_NAME=%%b
)
set RAPPath="\\127.0.0.1\C$\Program Files\HDUTILS\RAP"
cls
:connectIn
set /p remotepc= Enter the remote computer name or IP address:
if exist \\%remotepc%\C$\Users\ goto :inputUsername
echo Instruct user to restart the machine and log in.
SET tmout=3
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
echo.
goto :connectIn
:inputUsername
set /p remoteuser= Enter remote user's username:
if exist \\%remotepc%\C$\Users\%remoteuser%\ goto :choice
echo Invalid username. Please verify the spelling and try again.
SET tmout=3
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
dir \\%remotepc%\C$\Users\
goto :inputUsername
echo.
:choice
echo.
FOR %%? IN (\\%remotepc%\C$\Users\%remoteuser%\NTUSER.DAT) DO (ECHO %remoteUser%'s %%~n?%%~x? file size is %%~z? bytes)
echo Profile corruption typically occurs around 5000000 bytes.
echo.
REM This user's NTUSER.DAT file is over by ___ bytes.
set /P continue=Do you want to continue rebuilding this profile?[Y/N]
if /I "%continue%" EQU "Y" goto :sendBackup
if /I "%continue%" EQU "y" goto :sendBackup
if /I "%continue%" EQU "N" goto :abandon
if /I "%continue%" EQU "n" goto :abandon
echo.
echo Error: Invalid Parameter. Please press either "y" or "n" to continue.
echo.
goto :choice
:abandon
cls
echo Standby. Restarting program...
SET tmout=3
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
goto :beginning
REM Copy over the EFS Cert backup file
:sendBackup
set remoteuserdesktop=\\%remotepc%\C$\Users\%remoteuser%\Desktop
robocopy %RAPPath%\ %remoteuserdesktop%\ Backup.bat
echo.
echo.
echo.
echo Instruct the user to run the file named Backup.bat on their desktop and
echo let you know when it finishes. When it is done running, the command window
echo will close and 3 files should have appeared on the Desktop. Tell them to
echo inform you when they see the Ctrl + Alt + Del screen.
echo.
echo.
echo.
:SIDexist
if exist \\%remotepc%\c$\users\%remoteuser%\Desktop\SID.txt goto :copySID
goto :SIDexist
:copySID
robocopy %remoteuserdesktop%\ %RAPPath%\ SID.txt
del %remoteuserdesktop%\SID.txt
echo Press any key to rename the profile...
echo.
echo.
pause>nul
:rename
Set CURRDATE=%TEMP%\CURRDATE.TMP
Set CURRTIME=%TEMP%\CURRTIME.TMP
DATE /T > %CURRDATE%
TIME /T > %CURRTIME%
Set PARSEARG="eol=; tokens=1,2,3,4* delims=/, "
For /F %PARSEARG% %%i in (%CURRDATE%) Do SET YYYYMMDD=%%l%%k%%j
Set PARSEARG="eol=; tokens=1,2,3* delims=:, "
For /F %PARSEARG% %%i in (%CURRTIME%) Do Set HHMM=%%i%%j%%k
Echo RENAME \\%remotepc%\C$\Users\%remoteuser% old_%remoteuser%_%YYYYMMDD%%HHMM%
RENAME \\%remotepc%\C$\Users\%remoteuser% old_%remoteuser%_%YYYYMMDD%%HHMM%
set oldusername=old_%remoteuser%_%YYYYMMDD%%HHMM%
echo old_%remoteuser%_%YYYYMMDD%%HHMM% >oldprofile.txt
powershell -Command "(gc oldprofile.txt) -replace ' ', '' | Out-File oldprofile.txt"
powershell -Command "(gc oldprofile.txt) | ? {$_.trim() -ne '' } | set-content oldprofile.txt"
:choice2
if exist \\%remotepc%\C$\Users\old_%remoteuser%_%YYYYMMDD%%HHMM% goto :regKeyDelete
goto :uhoh
:uhoh
echo Inform the user you will restart their computer momentarily. Tell them to let
echo you know when they see the 'Ctrl + Alt + Del'screen.
echo Verify network connectivity with the ping that is now running.
shutdown /r /m \\%remotepc% /c "Computer will not rename profile. When prompted for a green shutdown, press no. Press OK to continue." /d p:0:0
start cmd.exe #cmd /k "ping -t %remotepc%"
echo.
echo Wait 60 seconds after the machine comes back online, then press any key to
echo continue the rebuild...
pause>nul
goto :rename2
:rename2
Set CURRDATE=%TEMP%\CURRDATE.TMP
Set CURRTIME=%TEMP%\CURRTIME.TMP
DATE /T > %CURRDATE%
TIME /T > %CURRTIME%
Set PARSEARG="eol=; tokens=1,2,3,4* delims=/, "
For /F %PARSEARG% %%i in (%CURRDATE%) Do SET YYYYMMDD=%%l%%k%%j
Set PARSEARG="eol=; tokens=1,2,3* delims=:, "
For /F %PARSEARG% %%i in (%CURRTIME%) Do Set HHMM=%%i%%j%%k
Echo RENAME \\%remotepc%\C$\Users\%remoteuser% old_%remoteuser%_%YYYYMMDD%%HHMM%
RENAME \\%remotepc%\C$\Users\%remoteuser% old_%remoteuser%_%YYYYMMDD%%HHMM%
set oldusername=old_%remoteuser%_%YYYYMMDD%%HHMM%
echo old_%remoteuser%_%YYYYMMDD%%HHMM% >oldprofile.txt
powershell -Command "(gc oldprofile.txt) -replace ' ', '' | Out-File oldprofile.txt"
powershell -Command "(gc oldprofile.txt) | ? {$_.trim() -ne '' } | set-content oldprofile.txt"
goto :choice3
:choice3
echo.
if exist \\%remotepc%\C$\Users\old_%remoteuser%_%YYYYMMDD%%HHMM% goto :regKeyDelete
goto :rename2
:regKeyDelete
REM Delete registry key
cd "C:\Program Files\HDUTILS\RAP\"
set /p Build=<SID.txt
reg delete "\\%remotepc%\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%Build%"
echo \\%remotepc%\C$\Users\old_%remoteuser%_%YYYYMMDD%%HHMM% >oldprofile.txt
echo.
echo.
echo Instruct the User to log in.
SET tmout=3
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
echo Waiting on customer login...
echo.
:listrebuilt
if exist \\%remotepc%\C$\Users\%remoteuser%\Desktop goto :nextplease
goto :listrebuilt
:nextplease
set remoteuserdesktop=\\%remotepc%\C$\Users\%remoteuser%
powershell -Command "(gc oldprofile.txt) -replace ' ', '' | Out-File oldprofile.txt"
powershell -Command "(gc oldprofile.txt) | ? {$_.trim() -ne '' } | set-content oldprofile.txt"
:copymigrationTools
robocopy %RAPPath%\ %remoteuserdesktop%\ oldprofile.txt
robocopy %RAPPath%\ %remoteuserdesktop%\ "Profile Migration Tool.bat"
robocopy %RAPPath%\ %remoteuserdesktop%\ "Map All PST files.vbs"
:checkFiles
if exist %remoteuserdesktop%\oldprofile.txt goto :checkPMT
goto :recopyProfile
:checkPMT
if exist "%remoteuserdesktop%\Profile Migration Tool.bat" goto :checkPST
goto :recopyPMT
:checkPST
if exist "%remoteuserdesktop%\Map All PST files.vbs" goto :finish
goto :recopyPST
:recopyProfile
robocopy %RAPPath%\ %remoteuserdesktop%\ oldprofile.txt
goto :checkFiles
:recopyPMT
robocopy %RAPPath%\ %remoteuserdesktop%\ "Profile Migration Tool.bat"
goto :checkFiles
:recopyPST
robocopy %RAPPath%\ %remoteuserdesktop%\ "Map All PST files.vbs"
goto :checkFiles
:finish
echo.
echo You have completed your end of the rebuild. MSRA in (to monitor everything)
echo and run 'Profile Migration Tool.bat' file to begin the migration process.
echo While everything is migrating, verify the user knows how to map network drives
echo and printers.
echo restart in 20 seconds.
(
echo Profile Rebuilt
echo Backup up EFS Certificates to desktop.
echo Network drives and printers backed up to a text file on user's desktop.
echo Appended 'old_' to the beginning of the local profile name and the date and time of rebuild to the end.
echo Backup of the profile registry key exported the old profile's 'Contacts' folder.
echo Agent instructed the user to log in.
echo Copied the Profile Migration Tool to the user's Desktop.
echo Data copied from old profile, EFS certificates restored ) | clip
echo.
echo A copy of all steps taken have been sent to the clipboard. Please paste these into your ticket.
SET tmout=10
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
goto :beginning

delete batch script not working

#ECHO OFF
Set LOG="C:\Temp\Copy_Delete.log"
::##############################################
::Begin Deleting
::##############################################
Set Sourcedir="C:\test"
Echo %date% %time%: "Deleting from %sourcedir% >> %LOG%
FORFILES /P "%Sourcedir%" /D +0 /C "cmd /c del #path %Sourcedir%" >> %LOG%
When i executed this ,delete didn't work and in the log file it shows
C:\test*, Are you sure (Y/N)? and at the command prompt it gives this message "Fri 11/08/2013 16:11:43.28: "Deleting from "C:\test" >> "C:\Temp\Copy_Delete.log"
what could be the issue here.
Try passing quiet flag to del command.
del /Q #path %Sourcedir%" >> %LOG%
This worked under Windows 7 Pro:
#ECHO OFF
Set LOG="C:\Temp\Copy_Delete.log"
::##############################################
::Begin Deleting
::##############################################
Set Sourcedir="C:\test"
Echo %date% %time%: Deleting from %sourcedir% >> %LOG%
FORFILES /P "%Sourcedir%" /D +0 /C "cmd /c IF #ISDIR==FALSE DEL #path" >> %LOG%
It deletes all files modified today in C:\test .

Resources