As part of my job I need to remove files from computers that are being shipped over seas, this task is done several times a week and can be scripted, however I am terrible with script, I am in no means a coder of any sort.
My issue is that I need to clear out the C:\Users folder whilst keeping the Public and Default folders. I know how to remove a directory and all subfolders however I don't know how to keep just those two folders.
The code I have so far is:
#Echo off
color F
:Choice
Echo.
Echo.
set choice=
set /p choice="Type Y to proceed or N to close the tool and then press ENTER:----"
IF '%Choice%' =='Y' GOTO DELETE
IF '%Choice%' =='y' GOTO DELETE
IF '%Choice%' =='N' GOTO END
IF '%Choice%' =='n' GOTO END
:DELETE
rmdir /S /Q C:\***PATH***\***FOLDERNAME***
rmdir /S /Q C:\***PATH***\***FOLDERNAME***
rmdir /S /Q C:\***PATH***\***FOLDERNAME***
rmdir /S /Q C:\***PATH***\***FOLDERNAME***
Echo.
Echo.
#Echo All Files Removed
GOTO END
:END
echo.
echo.
Echo *****...Closing programme... Please wait...*****
Timeout /t 3
exit
Do you know if this is possible?
The following method, ran As Administrator, may work for you:
#Echo Off
Color 0F
Echo=&Echo=
Choice /N /M "Type Y to proceed or N to close the tool"
If ErrorLevel 2 Exit /B
For /F Tokens^=2^Delims^=^" %%A In ('WMIC Path Win32_UserProfile Where^
"Special!='True'" Assoc /AssocClass:Win32_UserAccount 2^>Nul'
) Do WMIC UserAccount Where "SID='%%A' And LocalAccount='TRUE'" Delete
Echo=&Echo=&Echo All Files Removed&Echo=&Echo=
Echo *****...Closing programme... Please wait...*****
Timeout 3 /NoBreak>Nul
Exit /B
Special!='True' will ignore special accounts, which include Administrator, Public and Default.
Related
How could we find duplicated files in a certain folder and its sub-folders with also the possibility to eliminate them at the user's will?
Well, this is a way i found that this could be possible. The file and directory are not variable, are fixed and the user would have to edit the code in the program each time it wanted another file and/or another directory to work with.
I recently asked a question about my program and as promissed i would share it when it would be completed.
The program finds the duplicates in a folder and sub-folders of the directory chosen, lists them by order from ancient to the most recent one and it gives the user the choice to eliminate the files, file by file, at the user's will (telling the user which file is up to being deleted/eliminated).
Im very new to this kind of programming so if it is not the prettiest of programs im sorry, but it works and i haven't found something like this anywhere. I hope this helps someone!
#echo off
setlocal EnableDelayedExpansion
set "source_folder=C:\Desktop\Batch testes\Teste 1\Giorgio.docx"
echo Welcome to this Practice/Test Program
echo This program has the obective of finding duplicated files.
pause
echo The user will have the chance to eliminate these files if he wishes
echo There will be the identification of the oldest and the newest file
pause
echo Let us start...
pause
:aPrompt
cls
echo ========================================
echo What do you wish to do?
echo 1.Show only the duplicated files. (Clique '1')
echo 2.Show the duplicated files and eliminate them. (Clique '2')
echo 3.Exit the program (Clique '3')
choice /n /c:123 /M "Escolha uma opcao "%1
goto Alfa-%errorlevel%
:Alfa-1 A1
echo Showing the files being analysed
forfiles /P "C:\Desktop\Batch testes\Teste 1" /M Giorgio.docx /S /C "cmd /c echo #file"
echo Showing the paths of the files being analysed
forfiles /P "C:\Desktop\Batch testes\Teste 1" /M Giorgio.docx /S /C "cmd /c echo #relpath#fname"
pause
echo ===============================================================================
echo.
echo The files are set by order from the oldest (on top) to the most recent (on the bottom)
echo.
(for /f "delims=" %%a in ('dir /a-d /t:w /s /b "C:\Desktop\Batch testes\Teste 1\*Giorgio.docx"') do #echo %%~Ta %%a)
echo.
echo The oldest file is on top of the list. The most recent file is at the bottom of the list
echo.
echo=======================
echo=======================
pause
:bPrompt
echo Here are the duplicated files
echo Do you wish to leave or go back? (Type '1' to end the program, '2' to return to the previous menu)
choice /n /c:12 /M "Pick an option "%1
goto Bravo-%errorlevel%
:Bravo-1 B
echo The program will now end
pause
exit
:Bravo-2 B
echo You chose to go back
pause
goto :aPrompt
:Alfa-2 A2
echo You chose to show and eliminate the duplicated files
pause
echo Showing the files paths
forfiles /P "C:\Desktop\Batch testes\Teste 1" /M Giorgio.docx /S /C "cmd /c echo #relpath#fname"
echo Files identyfied by the the program (it serves the purpose of confirming if they are the right files)
forfiles /P "C:\Desktop\Batch testes\Teste 1" /M Giorgio.docx /S /C "cmd /c echo #file"
echo The files are set by order from the oldest (on top) to the most recent (on the bottom)
echo.
(for /f "delims=" %%a in ('dir /a-d /t:w /s /b "C:\Desktop\Batch testes\Teste 1\*Giorgio.docx"') do #echo %%~Ta %%a)
echo.
echo The oldest file is on top of the list. The most recent file is at the bottom of the list
echo You sure you want to delete the files? (Type '1' to eliminate them, '2' to not eliminate)
:cPrompt
choice /n /c:12 /M "Pick an option "%1
goto Charlie-%errorlevel%
:Charlie-1 C1
echo You chose to delete the files
echo The files will be deleted according to your decision
echo For each file it will be asked if you wish to delete it
pause
del /p /s "C:\Desktop\Batch testes\Teste 1"\*Giorgio.docx
echo The files have been deleted at your choice
pause
:dPrompt
echo Do you wish to exit the program or go back? (Type '1' to end the program, type '2' to go back to the main menu)
choice /n /c:12 /M "Pick an option "%1
goto Delta-%errorlevel%
:Delta-1 D1
echo You chose to leave. The program will shut down
pause
exit
:Delta-2 D2
echo You chose to go back to the main menu
pause
goto :aPrompt
:Charlie-2 C2
:ePrompt
echo You chose not to delete the files.
echo Do you wish to go back to the main menu or to leave? (Type '1' to go back to the main menu, '2' to leave the program)
choice /n /c:12 /M "Pick an option "%1
goto Evo-%errorlevel%
:Evo-1 E1
echo You chose to go back to the main menu
pause
goto :aPrompt
:Evo-2 E2
echo You chose to exit the program. The program will shut down now
pause
exit
:Alfa-3 A3
echo The program will shut down then
pause
exit
If by any case something is failing/giving an error, tell me and i'll fix it because i may have copied something wrong by mistake (like a typo or a missing "(", something).
( I don't know how i could share my program without using the "ask a question" function, im sorry if i broke any rules of this website)
Special thanks to Stephan that helped me previously and without him i couldn't complete the part where i set the oldest and recent file!
I have a batch file which searches through a directory tree deleting generated file backups.
I want to edit the script to run the del command against the files found in the search, but I can't get it to work.
I've searched other threads and set it up similarly but without the expected results.
#echo off
pushd FILEPATH
echo Searching directories...
for /f "delims=" %%G in ('dir /b /s *.0**.rfa') do echo "%%G"
echo.
IF /I "%%G" == "" GOTO NOTFOUND
set /P delete="Delete files? [Y/N]: "
IF /I "%delete%" NEQ "Y" GOTO ENDOF
echo Deleting files...
echo.
del "%%G"
echo.
echo Done!
timeout 5
exit
:ENDOF
echo Aborted.
timeout 5
exit
:NOTFOUND
echo Found nothing.
timeout 5
exit
Result:
Deleting files...
Could Not Find FILEPATH\ %G
Done!
Do you really need the for loop? The following should work exactly as you want:
#echo off
dir /b /s "*.0*.rfa" || echo Found nothing. & goto :finish
choice /m "delete all? "
if errorlevel 2 echo Aborted. & goto :finish
echo Deleting files...
del /q /s "*.0*.rfa"
echo Done.
:finish
timeout 5
exit /b
I want to open every file that ends with .jar in my Downloads folder. My code doesn't work. What am I doing wrong and how do I achieve my end goal?
Code:
del /s /q "C:\Users\%USERNAME%\AppData\Roaming\.minecraft\session.*"
cls
:choice
cls
set /P c=Open the file? [Y/N]
if /I "%c%" EQU "Y" goto :start
if /I "%c%" EQU "N" goto :choice
goto :choice
:start
start "" "C:\Users\Home Computer\Downloads\????.jar"
del /s /q "C:\Windows\Prefetch\JAVA*.pf"
del /s /q "C:\Users\Home Computer\Recent\*.bat.lnk"
del /s /q "C:\Users\Home Computer\Recent\????.jar.*"
del /s /q "C:\Users\Home Computer\Recent\Downloads.lnk"
pause
Edit: I should also mention that the name of the .jar changes every time I re download it. I can't target it specifically by file name. The file name is always four characters.
Take a look at these two screenshots.
https://gyazo.com/579ebd940bcd74f3a3deeb05db7b337d
https://gyazo.com/ceaffd97bf1f1e81860036810b35fcd7
If the name of the file has same number of characters everytime, then you can use ? for each character instead of *.
Say the filename is 3 characters long, then you can write the command as:
start "" "C:\Users\Home Computer\Downloads\???.jar"
Maybe you can take some references from the link given below:
https://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/
try
start "" "C:\Users\Home Computer\Downloads\*.jar"
or
java -jar "C:\Users\Home Computer\Downloads\*.jar"
You could use the Where command to identify the name of the downloaded file. (Of course it will only identify it if you don't have more than one four character .jar file there).
#Echo Off
Del/S/Q "%AppData%\.minecraft\session.*" 2>Nul
:Pick
ClS
Choice /M "Open the file"
If ErrorLevel 3 GoTo :EOF
If ErrorLevel 2 GoTo Pick
If ErrorLevel 1 GoTo Start
GoTo :EOF
:Start
For /F "Delims=" %%A In ('Where "%UserProfile%\Downloads":"????.jar"'
) Do (Set "FullName=%%~fA" & Set "Name=%%~nxA")
Start "" "%FullName%"
Del/Q "%SystemRoot%\Prefetch\JAVA*.pf" 2>Nul
Del/Q "%UserProfile%\Recent\%~nx0.lnk" 2>Nul
Del/Q "%UserProfile%\Recent\%Name%.lnk" 2>Nul
Del "%UserProfile%\Recent\Downloads.lnk" 2>Nul
Timeout -1
You could even shorten it a little by deleting more than one of the shortcuts from the same delete line.The locations you've used for recent are effectively only links to the real location in modern Windows versions so you could replace %UserProfile%\Recent with %AppData%\Microsoft\Windows\Recent.
I make a Script which deletes all empty Folders with Subfolders in a Path.
Now i have to make, if a folder was created 2 days ago and its empty it should be deleted with the other empty folders that are older than 2 Days.And if not it should be not deleted.
And i also need/want to make that deleted Folder are written in a Log.
I made that with the 5 Filetypes but i dont know how this schould work with the Folders.
Im really new to Batch, so i dont know what i should do.
I checked Google but the Results did not match with my problem.
I hope someone can help me.
Here is my Code that i´ve written so far:
#echo off
::start path / Variables
set startdir="C:\Users"
::Initialize the Variable
set /a loop=0
::Directory c:\temp\ will be created, if the folder not exists
if not exist c:\temp\ md c:\temp\
::Create Logfile for Deleted Filetypes in C:\Log\LOG_Useless_File_Killer.txt
echo ----------------------------------- >> C:\Log\LOG_Useless_File_Killer.txt
echo Logfile from: %date% at %time% >> C:\Log\LOG_Useless_File_Killer.txt
echo. >> C:\Log\LOG_Useless_File_Killer.txt
::this 5 Filetypes are going to be deleted immediately
del C:\Users\Thumbs.db /f /q /s >> C:\Log\LOG_Useless_File_Killer.txt
del C:\Users\desktop.ini /f /q /s >> C:\Log\LOG_Useless_File_Killer.txt
del C:\Users\*.DS_Store /f /q /s >> C:\Log\LOG_Useless_File_Killer.txt
del C:\Users\*._DS_Store /f /q /s >> C:\Log\LOG_Useless_File_Killer.txt
del C:\Users\*.desktop /f /q /s >> C:\Log\LOG_Useless_File_Killer.txt
::Writes the directorys in c:\temp\tmp.txt.
dir /AD /b /s %startdir% > c:\temp\tmp.txt
::at goto start it will be start again
:start
::the Variable %loop% is increased by 1
set /a loop =%loop%+1
::at 5 --> goto exit
if %loop%==5 goto exit
::Under 5 --> goto start
else goto start
::deletes every empty folder which is written in C:\temp\tmp.txt
for /F "delims=" %%i in (c:\temp\tmp.txt) do rd "%%i"
::--> goto start and begins again
goto start
::%loop% has reached 5 --> exit
:exit
::Console window will be closed
exit
pause
exit
Pradeep is absolutely right about the best way to go is for files.
For deleting folders, try this:
FORFILES -p "" /D -15 /C "cmd /c IF #isdir == TRUE rd /S /Q #path"
/D is for number of days, you can play with command parameters to meet exact requirement.
You can also use environment variables too so you can easily only delete files on the user that is currently logged on. For example, you can use %HOMEPATH%\Desktop to get to the desktop of the current user. More environment variables here.
My working batch file scans a long list of remote servers, copies anything there to a local server, checks the log file for a keyword, and if the keyword is found sends an email. I noticed it is always sending emails, even with a blank log file.
I discovered both FOR loops are using the %1 variable for their output - as seen in ECHO %1 and each line of the called :servermove. For lack of a better explanation it is not resetting %1 to null between loops.
I reviewed almost a dozen SO posts and am somewhat confident using SETLOCAL ENABLEDELAYEDEXPANSION would resolve this. That is where my understanding ends and I am unsuccessful thus far.
Here is the relevant code:
SET DATE=%date:~4,2%-%date:~7,2%-%date:~10,4%
SET HH=%time:~0,2%
SET MN=%time:~3,2%
SET TSTAMP=Time Run is %HH%%MN%
SET DATETIME=%DATE% at %HH%%MN%
SET LOGFILE="\\nt980a3\CreditFileImagesTransmission\LogFiles\%DATETIME%-File Move Log.txt"
SET MailDst=
SET MailSrc=
SET MailSrcName=Center to LDSD File Mover
SET OKMailSub=A Branch Has Sent You Some Files
ECHO %DATETIME% > %LOGFILE%
ECHO. >> %LOGFILE%
FOR /F "tokens=1" %%A IN (%~dp0SourceServers.txt) DO CALL :ServerMove %%A
:cleanuplogs
PUSHD "\\nt980a3\CreditFileImagesTransmission\LogFiles" &&(
FORFILES /S /M *.txt /D -45 /C "CMD /C DEL /Q #path"
) & POPD
:mailtest
FOR /F "tokens=*" %%A IN (%LOGFILE%) DO CALL :searchlog "%%A"
:searchlog
ECHO %1 | find "\\nt">NUL
IF NOT ERRORLEVEL 1 GOTO successmail
GOTO exit
:successmail
IF EXIST %temp%\to.txt DEL %temp%\to.txt
FOR %%a IN (%MailDst%) DO ECHO %%a>>%temp%\to.txt
"%~dp0sendmail.exe" /TO=%temp%\to.txt /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%OKMailSub% /MESSAGE=%LOGFILE% /HOST=
:exit
EXIT
:ServerMove
DIR /S /B \\%1\CreditFileImagesTransmission\*.* >> %LOGFILE%
XCOPY /E /C /I /Y "\\%1\CreditFileImagesTransmission\*.*" "\\nt980a3\CreditFileImagesTransmission\%DATE%\%HH%%MN%\"
FOR /D %%P IN ("\\%1\CreditFileImagesTransmission\*.*") DO RMDIR "%%P" /Q /S
DEL /Q /S "\\%1\CreditFileImagesTransmission\*.*"
I tried changing :mailtest to use %%B in both instances but that also fails. Placing SETLOCAL ENABLEDELAYEDEXPANSION and its counterpart ENDLOCAL before one or the other loop and changing the %%A to !A! does not work either.
Would someone kindly point out the error in my ways and offer suggestions or resources that will help me resolve this?
%1 is the first parameter provided to the procedure - either from the command-line (in the main procedure) or the parameter following the procedure name in call :procedurename parameter1.
In your case, %1 to :servermove is an entry from SourceServers.txt and %1 to :searchlog is each line from %LOGFILE%.
Since you've censored your batch, what you've posted makes little sense. For instance, the :searchlogs routine will take the first line from %LOGFILE% and go to successmail or cleanlogs depending on whether that first line contains the target string \\nt. What it does from there, we can't tell.
We're faced with an XY problem - trying to fix a solution, not a problem.
First problem: Don't use date as a user-variable. It's a "magic variable" which contains the date but it's overridden by a specific set statement.
Having run :servermove for each entry in SourceServers.txt, you are
- accumulating a directory list from \CreditFileImagesTransmission\*.* on that server.
- copying those files to server nt980a3 with a date/timestamp but not including the source-servername so any duplicate name anywhere will overwrite an earlier version. I suggest you include %1 into your destination-name.
- deleting subdirectories
- deleting files.
I'd suggest you simply remove the directory \\%1\CreditFileImagesTransmission\, then re-create it.
I'd also suggest that you add an extra line
goto :eof
after the del /q /s... line. This will cause execution to be transferred to the end-of-file (the colon in :eof is required) and may seem superfluous, but it ensures that the routine has a defined endpoint - if you add a further routine, there is no way the :servermove routine will continue into your new code.
After each server has been processed, you proceed to the :cleanuplogs routine, which I presume deletes logs older than 45 days.
Your next statement is a real problem. What it will do is grab the very first line of the logfile (which contains "%DATE% at %HH%%MN%" with the date resolved as you've set at the start and it then processes this line in :searchlog; there is no \\nt in this line, so errorlevel is set to 1, and the batch proceeds to :EXIT (not a good label in my view, since it's a keyword); executes an exitand should terminate the batch.
This appears not to be what it is actually doing, and I'm at a loss to explain why.
I'd suggest changing
:mailtest
FOR /F "tokens=*" %%A IN (%LOGFILE%) DO CALL :searchlog "%%A"
:searchlog
ECHO %1 | find "\\nt">NUL
IF NOT ERRORLEVEL 1 GOTO successmail
GOTO exit
to
:mailtest
find "\\nt" %LOGFILE%>NUL
IF NOT ERRORLEVEL 1 GOTO successmail
:failmail
echo "\\nt" was found in the log
pause
GOTO exit
but I can't test that...
:mailtest
FOR /F "tokens=*" %%A IN (%LOGFILE%) DO CALL :searchlog "%%A"
You are missing a GOTO :EOF or similar goto here because it will drop through to the routine below once the above is finished.
:searchlog
ECHO %1 | find "\\nt">NUL
IF NOT ERRORLEVEL 1 GOTO successmail
GOTO exit
I feel you can not carry the %1 of first for loop to others. Try to transfer that to another variable like below.
:ServerMove
set servername=%1
DIR /S /B \\%servername%\CreditFileImagesTransmission\*.* >> %LOGFILE%
XCOPY /E /C /I /Y "\\%servername%\CreditFileImagesTransmission\*.*" "\\nt980a3\CreditFileImagesTransmission\%DATE%\%HH%%MN%\"
FOR /D %%P IN ("\\%servername%\CreditFileImagesTransmission\*.*") DO RMDIR "%%P" /Q /S
DEL /Q /S "\\%servername%\CreditFileImagesTransmission\*.*"
Cheers, G