Batch file to delete temp files on a remote workstation - file

I wrote an easy batch to basically ask me a server name and then it would go and delete the temp files out of the specified directories. Yes I know power shell would probably be way more effective but Im still pretty new to my Sysadmin position and the network is so large Im not ready to be mingling in that area yet.
But anyway I would love to be able to create a list of the servers and have it go through them all deleting these temp files instead of opening a new command window for each server and then executing my batch file. I either want to have the list of servers already in the batch file or have the batch call back to .txt file with the server list and then open a brand new cmd prompt window for each server and commence the deletion.
Here is what I have so far, Its simple, its easy, it works, but Im coming across imputing about 100 servers so that's about 6 command prompt windows at a time (to avoid confusion) letting them go through and delete and when they all finish open another 6 give them all another server then let them delete and ETC
:deleteit
echo off
echo ------------------------------------------------------
set /p server=Please enter the name of your workstation/server you wish to clean:
echo You have entered %server% as your workstation
pause
del "\\%server%\c$\temp\*.*" /s /f /q
del "\\%server%\c$\windows\temp\*.*" /s /f /q
del "\\%server%\c$\windows\ProPatches\Patches\*.*" /s /f /q
rd /s "\\%server%\c$\$Recycle.bin"
echo --------------------------------------------------
set /p choice=Again? (y/n)
if /i %choice%==Y (goto deleteit) else (goto end)
:end

Related

Delete a folder before exiting the command prompt window

I am working with a batch script in which the user can automate the creation of folders and subfolders on windows.
Here's the actual code:
#echo off
:: MAKES A TEMPORARY FOLDER FIRST
mkdir "New Folder 123"
:: LET THE USER INPUT PREFERED FOLDER NAME AND THIS WILL CHANGE THE TEMPORARY INTO THE NEW ONE
:rename
cls
SET /p comm=Please enter your prefered folder name:
IF /i "%comm%" == "%comm%" ren "New Folder 123" "%comm%"
IF /i "" == "%comm%" goto :rename
IF /i " " == "%comm%" goto :rename
:: COMMAND WILL OPEN THE NEWLY RENAMED FOLDER AND CREATES SUBFOLDER(S)
cd "%comm%"
md "Folder 1" "Folder 2"
exit
Now, the problem is... If the user accidentally exits the command prompt window, the temporary folder which I initially wrote from the beginning of the code remains.
:: MAKES A TEMPORARY FOLDER FIRST
mkdir "New Folder 123"
This will create a conflict if the user runs the batch script the second time since that temporary folder already exists and I don't want the user to manually right click and delete it cause that would be a hassle.
So I'm hoping if anyone could provide a code that will automatically delete the initial folder as the user (accidentally) exits the console? I've been looking for similar solutions here that are closely related to mine, but they all seems to delete the batch file itself instead of a folder, I'm also really new into making programs and I had a hard time understanding some batch codes, so please be easy with me, Any help would be greatly appreciated, Thank you so much everyone.
Just add this at the beggining of the file after #echo off
rmdir "New folder 123" /s /q >NUL 2>&1

Batch Script to copy folder from Server to user desktop in a network

My goal is to create a batch script to copy a folder with subfolders to user desktop with overwrite option and minimized of command prompt.
I am pushing the script through Group policy in user start up screen.
However I am getting an error when running the script locally. Not sure what I am missing in the script..
#echo off
#cls
if not "%minimized%"=="" goto :minimized
set minimized=true
start /min cmd /C "%~dpnx0"
goto :EOF
:minimized
echo Your Source Path:
set INPUT1=\\X.X.X.X\Test\TMS\
echo Your Destination Path:
set INPUT2=C:\Users\%Username%\Desktop\
xcopy %INPUT1% %INPUT2% /y /s
:minimized
You mentioned folder, so I am writing this assuming you want to create the TMS folder with content on the desktop.
I would try something like this inside of you minimized label. This is untested as I have no Network drives to test with.
for /f "tokens=2" %i in ('net use * "\\X.X.X.X\Test\TMS\" ^| findstr /i Drive') do set "tmpDr=%%i"
mkdir "%USERPROFILE%\Desktop\TMS" >nul
xcopy "%tmpDir%\*" "%USERPROFILE%\Desktop\TMS" /s /y
net use /d %tmpDir% >nul
Some things to note in your code. You have 2 minimized labels, you need to enclose path variables with double quotes to eliminate possible whitespace, you can drop the echo's seeing as you plan on running the script minimized. Last but not least, you do not need to specify full path to the user's desktop as %USERPROFILE% variable already exists as Drive:\Users\Username

create batch script file with user prompt and xcopy

I'm trying to create a batch script file to help an administrative assistant in my work group. Let's call him John.
John receives many CDs daily from clients containing architectural drawings as PDFs. Each CD is unique. John assigns it an Application Number, and creates a new folder on the network drive with the Application Number as the folder name. John then copies all the files on the CD to the newly created folder name. He repeats this process for every CD he receives.
I don't have any programming experience so I hope you can lend me a hand. Here's what I wrote below but it's not working. I get an "Insufficient memory" error. A new folder name based on the user input is correctly created on the network drive path but it's empty.
Thanks for your help! FYI, I'm running Windows 7 64-bit
#echo off
echo Welcome team member!
pause
set /p anumber=Type in the Application Number then press Enter key when done.
mkdir "S:\ARCH\Active Forms and Files\Submittal Floor Plans\%anumber%\"
:: e:\ is the CD drive path
set source=e:\
:: S:\ is a network drive
set destination="S:\ARCH\Active Forms and Files\Submittal Floor Plans\%anumber%\"
xcopy %source%\* %destination%\* /s /e /l /h /i >nul
pause
exit
You were setting the variable %source% to e:\ which was the read by the interpreter as E:\\* when used in %source%\*, leading to an invalid directory. The same was being done to the %destination% variable.
Updated Script:
#echo off
set "networkFolder=S:\ARCH\Active Forms and Files\Submittal Floor Plans"
set "CDDrive=e:"
echo Welcome team member!
:input
set "applicationNo="
set /p "applicationNo=Enter the Application Number and press ENTER: "
if not defined applicationNo goto :input
set "newLocation=%networkFolder%\%applicationNo%"
:actions
md "%newLocation%"
xcopy %CDDrive%\* "%newLocation%" /s /e /i /h>nul
echo Completed!
pause

Reg Query in script not working when executed remotely with psexec

I have recently gotten a script together for querying the reg for a temp folder path and cleaning the folder and it works great(Thanks Compo) but when used remotely with psexec it says, "The system was unable to find the specified registry key or value." Before I use PSEXEC to execute the batch I first have it copied to the C:\ and I use this to do that.
set /p cpu=
robocopy "\\nmcfs01\software\scripts\Jacob's Awesome Outlook Scripts" \\%cpu%\c$\Jacob'sTemp
That part goes well then I execute it with psexec with
psexec \\%cpu% -u administrator -i -d "C:\Jacob'sTemp\compo.bat"
That connects but when it executes the batch file it does not find the reg key. HOWEVER, if I go to the C:\Jacob'sTemp and double click on the compo.bat file it works fine and deletes out the files. Also, if I just use PSEXEC to execute it again outside of this script just separately after it is copied over it still does not work. Here is the script I am using for cleaning it up.
#Echo Off
SetLocal EnableExtensions
(Set OV=14.0)
Choice /C YN /M "Delete Outlook Temp Files?"
If ErrorLevel 2 Exit/B
Set "BK=HKCU\SOFTWARE\Microsoft\Office\"
Set "EK=\Outlook\Security"
Set "VN=OutlookSecureTempFolder"
For /F "Tokens=2*" %%I In ('Reg Query "%BK%%OV%%EK%" /V %VN%') Do Set "VD=%%J"
PushD "%VD%" && (RD/S/Q "%VD%" 2>Nul) && PopD
pause
REM The below commands will empty Jacob'sTemp:
If Exist "%SystemDrive%\Jacob'sTemp" (PushD "%SystemDrive%\Jacob'sTemp" && (
(RD/S/Q "%SystemDrive%\Jacob'sTemp" 2>Nul) && PopD
pause
REM The below commands without the first two characters will remove Jacob'sTemp
If Exist "%SystemDrive%\Jacob'sTemp" (RD/S/Q "%SystemDrive%\Jacob'sTemp"
Pause
Echo(------------------------------------------------------------------------------
Echo( Complete! Goodbye!
Echo(------------------------------------------------------------------------------
Timeout 5 >Nul
It would be a huge help to have this work as intended where we can just type the computer name in and done but I do not know why it does not work when executed remotely and it is copied to the computer. Any help is much appreciated!
HKCU, the target of your reg query, is a per user registry hive. psexec's remote service runs in SYSTEM account and when it issues reg query that wont be directed to the remote machine's currently logged-in user's HKCU. It would be directed to the SYSTEM account's HKCU which maps under HKEY_USERS\S-1-5-18\Software.... Hence the error "The system was unable to find the specified registry key or value."

Add error handling to existing Windows batch script-> to copy the newest file from a directory

I found a good post here that queries for the latest sql server backup, and then copies it over to the remote server in preparation for a restore. It's a batch file that is executed using cmd via sql agent step inside the sql restore job. I'm looking for help in adding extra logic to the existing script below:
:Variables
SET DatabaseBackupPath=\\virtualserver1\Database Backups
echo.
echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"
What I'd like to add are two extra pieces. First add some error handling to the existing script where it would first check the latest backup, but ensure its within the last 24 hours. If it is continue to run. If older than 24 hours, to generate an notification alert (i.e. separate batch file) if backup file is older than 24 hours. Second to generate similar notification, if there was an issue such as not being able to reach the remote share that holds the backup.
Appreciate replies.
It is not easy to check if a file was created or last modified within 24 hours. Date/time calculation is not a trivial task without conversion of the date/time strings to seconds since epoch which would make it possible to use a simple integer comparison.
There are solutions for file date comparison, see
Batch script to check when the newest file in a directory was created/modified
forfiles - Delete all files older than 1 day / 24hours using creation date?
You may use one of those solutions.
Much easier is to check if copy process worked:
copy /V "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"
if errorlevel 1 goto CopyFail
goto :EOF
:CopyFail
echo.
echo Copying file "%DatabaseBackupPath%\WebServer\%NewestFile%" failed!
pause
Solution using WinRAR
My solution below is based on usage of Rar.exe, the console version of WinRAR as this compression tool has the feature to compress only files based on file dates. Therefore this solution is only helpful for you if you have installed WinRAR and bought a license of it.
The path of the program files folder of WinRAR must be set at top of the following batch file.
#echo off
SET DatabaseBackupPath=\\virtualserver1\Database Backups
SET WinRarFolder=C:\Program Files\WinRAR
cls
echo.
echo Restore WebServer Database
echo.
rem Find newest *.bak file in backup directory on server.
FOR /F "delims=" %%I IN ('DIR /B /O-D "%DatabaseBackupPath%\WebServer\*.bak"') DO (
SET NewestFile=%%I
goto BackupFound
)
cls
echo.
echo Restore WebServer Database
echo.
echo There is no *.bak file in "%DatabaseBackupPath%\WebServer\"
echo or the backup directory on server cannot be reached at all.
goto EndBatch
:BackupFound
echo Newest backup in "%DatabaseBackupPath%\WebServer"
echo is the file "%NewestFile%".
echo.
if exist "%TEMP%\ServerBackup.rar" del "%TEMP%\ServerBackup.rar"
"%WinRarFolder%\Rar.exe" a -cfg- -ep -inul -m0 -tn24h -y "%TEMP%\ServerBackup.rar" "%DatabaseBackupPath%\WebServer\%NewestFile%"
if errorlevel 1 goto OldBackup
"%WinRarFolder%\Rar.exe" e -cfg- -inul -y "%TEMP%\ServerBackup.rar" F:\Temp
if errorlevel 1 goto ExtractFailed
del "%TEMP%\ServerBackup.rar"
echo File "%NewestFile%" copied to D:\
goto EndBatch
:ExtractFailed
del "%TEMP%\ServerBackup.rar"
echo "Copying file "%NewestFile%" to D:\ failed.
goto EndBatch
:OldBackup
echo File "%NewestFile%" is older than 24 hours.
:EndBatch
set WinRarFolder=
SET DatabaseBackupPath=
SET NewestFile=
echo.
pause
Explanation:
The batch file first uses command DIR to get a list of *.bak files in the specified directory sorted according to last modification file date from newest to oldest.
With the FOR loop the name of the file name at top of the list (= newest file) is assigned to environment variable NewestFile.
The batch file outputs an error message if no *.bak file can be found in the specified directory, for example if the server cannot be reached at all at the moment with the permissions of the used user account.
But on success on finding a *.bak file in specified directory, the batch file informs the batch file user which file was found in which directory.
After making sure that the RAR archive to create next does not already exist in directory for temporary files, Rar.exe is used to create a RAR archive in directory for temporary files into which only the found file is stored without compression, but only if this file has a last modification date within 24 hours because of switch -tn24h.
For details on the switches used on Rar.exe see text file Rar.txt in program files directory of WinRAR.
Rar.exe exits with an return value greater 0 if there is any problem on creating the RAR archive. In this case the reason is most likely that the specified file is older than 24 hours which results now in an appropriate message written into the console window.
Rar.exe is on success on creating the RAR archive without compression used once more to extract the file to target directory.
An appropriate error mesage is shown in unlikely case that this fails. Otherwise the batch file outputs a success message and finishes with cleaning up environment table (not really needed if command prompt window closed next).
The temporarily used RAR archive is deleted in any case.

Resources