Batch file to delete files from users on network - file

I want the batch file to ask for Serial number and username and delete two specific folders from users profile. I made this but it seems to want to delete *.* from folder I am running it from.
#echo off
set /p serial="Enter Serial: "
set /p username="Enter Username: "
del *.* \\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\AutomaticDestinations
del *.*
\\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\CustomDestinations
pause

Try next approach with basic checking all user's input:
#ECHO OFF
SETLOCAL EnableExtensions
:inputServer
set "serial="
set /p "serial=Enter Serial: "
if not defined serial goto :endlocal
pushd "\\%serial%\C$\"
if errorlevel 1 (
echo wrong server name "\\%serial%"
goto :inputServer
)
:inputUser
set "_username="
set /p "_username=Enter Username: "
if not defined _username goto :endstack
cd "\users\%_username%\appdata\roaming\Microsoft\Windows\Recent"
if errorlevel 1 (
echo wrong user name "%_username%" or path
echo "\\%serial%\C$\users\%_username%\appdata\roaming\Microsoft\Windows\Recent"
goto :inputUser
)
dir AutomaticDestinations\*.*
dir CustomDestinations\*.*
:endstack
popd
:endlocal
pause
Replace dir with del /Q no sooner than debugged.
Resource for PUSHD - POPD pair:
When a UNC path is specified, PUSHD will create a temporary drive
map and will then use that new drive. The temporary drive letters are
allocated in reverse alphabetical order, so if Z: is free it will be
used first.

c$ is administrator hiding ressources, you can't access to it without login
If you want to connect to network share on the remote computer, use this:
net use * \servername\sharename

The syntax of the del command does not allow to separate the file mask from the path where the files to delete are stored, so you need to use
del /q "\\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\AutomaticDestinations\*.*"
del /q "\\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\CustomDestinations\*.*"
The added quotes will prevent problems with paths that include spaces and the /q switch will avoid the security confirmation to delete the all the files in the indicated folder.

First, remove the #echo off untill your code is working so you can see what's happening, then add some echo to see what is stored in the variable that you're using. After that try with DIR instead of DEL so it list the file that match your criteria.
REM #echo off
set /p serial="Enter Serial: "
Echo %serial%
pause
set /p username="Enter Username: "
echo %username%
pause
dir \\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\AutomaticDestinations\*.*
dir \\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\CustomDestinations\*.*
pause

Related

How to print only number of files copied as a variable, while logging all the actions?

I'm writing a script on a BAT file to use when necessary, to backup a folder of an application on several computers.
This script works on Windows 7: will it also work on Windows 10?
:: Backup script with logging
#echo off
net use \\SERVER\Shared_Folder userPassword /USER:userName
set PATH=c:\WINDOWS\system32;
set SRC="C:\Program Files (x86)\ApplicationName\TargetFolder"
set DST=\\SERVER\Shared_Folder\Backups
set LOG=%DST%\Backup_LogFile.log
echo:>>%LOG%
echo Backup from computer %COMPUTERNAME% >>%LOG%
echo Starts -- %DATE% %TIME% >>%LOG%
echo Wait please: backup is running...
xcopy %SRC% %DST%\%COMPUTERNAME%\ /A /D /E /J /Y /Z>>%LOG%
echo Ends -- %DATE% %TIME% >>%LOG%
echo:>>%LOG%
My script works fine but I want a better response on terminal for the user than execute it.
The script adds correctly the actions on a log file, but I want the user can see only the number of file copied not the list of all files copied.
Here is one way to accomplish what you ask. There are other ways too. The secret here is using "for /F" and sending each result to another function. The other function will log each line to a file. It will then look for xcopy's "File(s) copied" line and pipe that to the user if it sees it.
Also... note the "goto :EOF" statements. These tell the batch interpreter to return to the caller much like any other programming language.
I hope this does what you are asking. :)
:: Backup script with logging
#echo off
net use \\SERVER\Shared_Folder userPassword /USER:userName
set SRC="C:\Program Files (x86)\ApplicationName\TargetFolder"
set DST=\\SERVER\Shared_Folder\Backups
set LOG=%DST%\Backup_LogFile.log
echo:>>%LOG%
echo Backup from computer %COMPUTERNAME% >>%LOG%
echo Starts -- %DATE% %TIME% >>%LOG%
echo Wait please: backup is running...
for /f "delims=" %%f in ('xcopy %SRC% %DST%\%COMPUTERNAME%\ /A /D /E /J /Y /Z') do call :log_items "%%f"
echo Ends -- %DATE% %TIME% >>%LOG%
echo:>>%LOG%
goto :EOF
:log_items
Set InputLine=%~1
:: Log everything
echo %InputLine%>>%LOG%
:: Check if the line coming in contains "File(s) copied" if it doesn't, return
if "%InputLine:File(s) copied=%"=="%InputLine%" goto :EOF
:: If it does, show it to the user and return
echo %InputLine%
goto :EOF
The comparison done for the files copied looks like this:
For a line with your file name: (here they match so it returns)
C:\git\ps>if "test\targetver.h" == "test\targetver.h" goto :EOF
For a line with your number of files: (here they dont match do it doesn't return)
C:\git\ps>if "205 " == "205 File(s) copied" goto :EOF

Is there a way to create a persistent variable in batch file by writing to itself?

I have written a batch file that I use for file management. The batch file parses an .XML database to get a list of base filenames, then allows the user to move/copy those specific files into a new directory. The program prompts the user for a source directory and the name of the .XML file. I would like the program to default the variables to the last used entry, even if the previous CMD session has closed. My solution has been to ask the user for each variable at the beginning of the program, then write those variables to a separate batch file called param.bat at the end like this:
#echo off
set SOURCEDIR=NOT SET
set XMLFILE=NOT SET
if exist param.bat call param.bat
set /p SOURCEDIR=The current source directory is %SOURCEDIR%. Please input new directory or press [Enter] for no change.
set /p XMLFILE=The current XML database is %XMLFILE%. Please input new database or press [Enter] for no change.
REM {Rest of program goes here}
echo #echo off>param.bat
echo set SOURCEDIR=%SOURCEDIR%>>param.bat
echo set XMLFILE=%XMLFILE%>>param.bat
:END
I was hoping for a more elegant solution that does not require a separate batch file and allows me to store the variable data within the primary batch file itself. Any thoughts?
#echo off
setlocal
dir /r "%~f0" | findstr /c:" %~nx0:settings" 2>nul >nul && (
for /f "usebackq delims=" %%A in ("%~f0:settings") do set %%A
)
if defined SOURCEDIR echo The current source directory is %SOURCEDIR%.
set /p "SOURCEDIR= Please input new directory or press [Enter] for no change. "
if defined XMLFILE echo The current XML database is %XMLFILE%.
set /p "XMLFILE=Please input new database or press [Enter] for no change. "
(
echo SOURCEDIR=%SOURCEDIR%
echo XMLFILE=%XMLFILE%
) > "%~f0:settings"
This uses the Alternate Data Stream (ADS) of the batchfile to
save the settings.
NTFS file system is required. The ADS stream is lost if the
batchfile is copied to a file system other than NTFS.
The dir piped to findstr is to determine if the
stream does exist before trying to read from it.
This helps to avoid an error message from the for
loop if the ADS does not exist.
The for loop sets the variable names and values read from the ADS.
Finally, the variables are saved to the ADS.
Note:
%~f0 is full path to the batchfile.
See for /? about all modifiers available.
%~f0:settings is the batchfile with ADS named settings.
dir /r displays files and those with ADS.
Important:
Any idea involving writing to the batchfile could result
in file corruption so would certainly advise a backup of
the batchfile.
There is one way to save variables itself on the bat file, but, you need replace :END to :EOF
:EOF have a good explained in this link .:|:. see Where does GOTO :EOF return to?
Also, this work in fat32/ntfs file system!
You can write the variables in your bat file, and read when needs:
Obs.: Sorry my limited English
#echo off & setlocal enabledelayedexpansion
set "bat_file="%temp%\new_bat_with_new_var.tmp"" & type nul >!bat_file! & set "nop=ot Se"
for /f %%a in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo 0x40"') do set "delim=%%a"
type "%~f0"| findstr "!delim!"| find /v /i "echo" >nul || for %%s in (SOURCEDIR XMLFILE) do set "%%s=N!nop!t"
if defined SOURCEDIR echo/!SOURCEDIR!%delim%!XMLFILE!%delim%>>"%~f0"
for /f "delims=%delim% tokens=1,2" %%a in ('type "%~f0"^| findstr /l "!delim!"^| find /v /i "echo"') do (
set /p "SOURCEDIR=The current source directory is %%~a. Please input new directory or press [Enter] for no change: "
set /p "XMLFILE=The current XML database is %%~b. Please input new database or press [Enter] for no change: "
if /i "!old_string!" neq "!SOURCEDIR!!delim!!XMLFILE!!delim!" (
type "%~f0"| findstr /vic:"%%~a!delim!%%~b!delim!">>!bat_file!"
copy /y !bat_file! "%~f0" >nul
echo/!SOURCEDIR!!delim!!XMLFILE!!delim!>>%~f0"
goto :_continue_:
))
:_continue_:
rem :| Rest of program goes here | replace/change last command [goto :END] to [goto :EOF]
goto :EOF
rem :| Left 2 line blank above, because your variable will be save/read in next line above here |:

CMD deleting folder recursively (i.e. same folder name in multiple locations)

Due to a Dreamweaver setting mess-up, we've had thousands of "_notes" folders pop up in our websites dev & qa areas. There's too many to delete through Windows Explorer - everything just locks up - so I was hoping to run a batch script to sort it out for us once and for all. The problem is I'm not entirely sure that "rd /S" will do what I want.
My understanding is that rd /S will look recursively in the folder I tell it, so if I say:
rd /S r:/<siteName>/_notes/
then it will just look in the _notes folder and delete what's in there and then try to move further down that tree. What I need is a script that would take into account things like the following:
r:/<siteName>/_notes/
r:/<siteName/<someFolder>/_notes/
r:/<siteName/<someOtherFolder>/_notes/
r:/<siteName/<someFolder>/<someSubFolder>/_notes/
r:/<siteName/<someFolder>/<iThinkIveMadeMyPoint>/_notes/
Hope I made sense...
I found this in another thread, but it doesn't work with folders with a . in the name, so it's no use for site names...
#Echo OFF
REM Important that Delayed Expansion is Enabled
setlocal enabledelayedexpansion
REM This sets what folder the batch is looking for and the root in which it starts the search:
set /p foldername=Please enter the foldername you want to delete:
set /p root=Please enter the root directory (ex: C:\TestFolder)
REM Checks each directory in the given root
FOR /R %root% %%A IN (.) DO (
if '%%A'=='' goto end
REM Correctly parses info for executing the loop and RM functions
set dir="%%A"
set dir=!dir:.=!
set directory=%%A
set directory=!directory::=!
set directory=!directory:\=;!
REM Checks each directory
for /f "tokens=* delims=;" %%P in ("!directory!") do call :loop %%P)
REM After each directory is checked the batch will allow you to see folders deleted.
:end
pause
endlocal
exit
REM This loop checks each folder inside the directory for the specified folder name. This allows you to check multiple nested directories.
:loop
if '%1'=='' goto endloop
if '%1'=='%foldername%' (
rd /S /Q !dir!
echo !dir! was deleted.
)
SHIFT
goto :loop
:endloop
read HELP FOR, HELP SET and HELP IF
note that FOR /D /R will recursively walk the directory tree.
note also that %~na is the funny syntax to extract the name part of a full path.
so, putting this little pieces togethere, try this command on the command line
for /d /r %a in (*) do #if %~na==_notes #echo rd %a
after careful testing, remove the echo command.
This command has worked for me and I hope this could help. Switch to the common root folder, and type in CMD:
for /d /r . %d in (<folder name>) do #if exist "%d" rd /s/q "%d"
Change the to the name of folder you want to remove. Then all children folders with this name would be removed.

I Want To Copy Files with set /p On Batch

I want to copy a file with set /p. Task: Write a file name with set /p and that will be copied in a directory that I want, but it doesn't work.
My current source:
#echo off
echo Enter YOur Pic Name With .jpg
set /p cop=
xcopy /s %systemroot%\%cop% %systemroot%\system32\oobe\info\backgrounds
cls
pause
For the SET /P command, the format works best like this:
set /p cop=Enter your Pic name with .jpg
I'd also suggest you add a couple of lines to check if the file is actually there:
#rem just check that the full path is what I expect
echo %systemroot%\%cop%
#rem and check if the file is there
dir %systemroot%\%cop%
(Delete these lines once your batch file is working).
Also, delete the cls line, until it's working. Then, once it's doing what you need, you can put it back in, if you want.
You might want to think about whether %systemroot% is the right place for these pictures, even temporarily. It's usually used for Windows OS code.
It is possible that %systemroot% path may have spaces, so file names must be enclosed in quotes:
#echo off
set /p "cop=Enter YOur Pic Name With .jpg: "
xcopy /s "%systemroot%\%cop%" "%systemroot%\system32\oobe\info\backgrounds"
cls
pause
try running as admin: http://windows.microsoft.com/en-us/windows7/how-do-i-run-an-application-once-with-a-full-administrator-access-token
also you may try the following (xcopy doesn't like the /s), I think you're trying to silence the output, just try with the >nul redirect:
#echo off
echo Enter YOur Pic Name With .jpg
set /p cop=
xcopy /y %systemroot%\%cop% %systemroot%\system32\oobe\info\backgrounds\* >nul
cls
pause

uTorrent Batch Script

I wrote myself a script based off another one that I found and I'm having trouble figuring out why it's not working.
How it is supposed to work is once a torrent has finished downloading, it runs the script and grabs the Label on the torrent. For testing, I was downloading a song with the label of Music.
When it gets to the point at :copyfile, it won't move it into the correct directory. Instead of moving into F:\Completed Torrents\Music, it just moves into F:\Completed Torrents.
Can someone please point out what I'm missing because I've looked through it thrice already and it's driving me crazy. The script is below.
#echo off
title Liam's torrent-file script
rem Parameter usage: fromdir torrent-name label kind [filename]
rem corresponds to uTorrents flags: %D %N %L %K %F
echo *********************************************
echo Run on %date% at %time%
set fromdir=%1
set name=%2
set label=%3
set kind=%4
set filename=%5
set savepartition="F:\Completed Torrents"
set winrar="C:\Program Files (x86)\WinRAR\WinRAR.exe"
set torrentlog="F:\Torrent Scripts\logs\torrentlog.txt"
set handledlog="F:\Torrent Scripts\logs\handled_torrents.txt"
set errorlog="F:\Torrent Scripts\logs\ErrorLog.txt"
set label_prefix=""
echo Input: %fromdir% %name% %label% %kind% %filename%
rem Check if the label has a sub label by searching for \
if x%label:\=%==x%label% goto skipsublabel
rem Has a sub label so split into prefix and suffix so we can process properly later
echo sub label
for /f "tokens=1,2 delims=\ " %%a in ("%label%") do set label_prefix=%%a&set label_suffix=%%b
rem add the removed quote mark
set label_prefix=%label_prefix%"
set label_suffix="%label_suffix%
echo.prefix : %label_prefix%
echo.suffix : %label_suffix%
goto:startprocess
:skipsublabel
echo Skipped Sub Label
goto:startprocess
:startprocess
echo %date% at %time%: Handling %label% torrent %name% >> %handledlog%
rem Process the label
if %label%=="Movies" goto known
if %label%=="Music" goto known
if %label_prefix%=="TV" goto TV
rem Last resort
rem Double underscores so the folders are easier to spot (listed on top in explorer)
echo Last Resort
set todir=%savepartition%\Unsorted\__%name%
if %kind%=="single" goto copyfile
if %kind%=="multi" goto copyall
GOTO:EOF
:known
echo **Known Download Type - %label%
set todir=%savepartition%\%label%\%name%
echo todir = %todir%
GOTO:process
:TV
echo **Known Download Type - %label%
set todir=%savepartition%\%label_prefix%\%label_suffix%
echo todir = %todir%
GOTO:process
:process
rem If there are rar files in the folder, extract them.
rem If there are mkvs, copy them. Check for rars first in case there is a sample.mkv, then we want the rars
if %kind%=="single" goto copyfile
if exist %fromdir%\*.rar goto extractrar
if exist %fromdir%\*.mkv goto copymkvs
if %kind%=="multi" goto copyall
echo Guess we didnt find anything
GOTO:EOF
:copyall
echo **Type unidentified so copying all
echo Copy all contents of %fromdir% to %todir%
xcopy %fromdir%\*.* %todir% /S /I /Y
GOTO:EOF
:copyfile
rem Copies single file from fromdir to todir
echo Single file so just copying
echo Copy %filename% from %fromdir% to %todir%
xcopy %fromdir%\%filename% %todir%\ /S /Y
GOTO:EOF
:copymkvs
echo Copy all mkvs from %fromdir% and subdirs to %todir%
xcopy %fromdir%\*.mkv %todir% /S /I /Y
GOTO:EOF
:extractrar
echo Extracts all rars in %fromdir% to %todir%.
rem Requires WinRar installed to c:\Program files
if not exist %todir% mkdir %todir%
IF EXIST %fromdir%\subs xcopy %fromdir%\subs %todir% /S /I /Y
IF EXIST %fromdir%\subtitles xcopy %fromdir%\subtitles %todir% /S /I /Y
call %winrar% x %fromdir%\*.rar *.* %todir% -IBCK -ilog"%todir%\RarErrors.log"
IF EXIST %fromdir%\*.nfo xcopy %fromdir%\*.nfo %todir% /S /I /Y
GOTO:EOF
EDIT
Also, for some reason, on line 39 nothing prints to the log. For those who wish to see the code with line numbers: http://hastebin.com/juqokefoxa.dos
A couple of bits for ya:
1) Likely, your script isn't moving the files. Preferences / Directories has an option to move downloads when completed. verify that these settings aren't doing the file moving.
2) uTorrent locks the files on completion so that seeding can continue. To change this behavior, go to Preferences / Advanced and set bt.read_only_on_complete to false
3) you will still be foiled because "Run this program when a torrent finishes" doesn't really do what it says. It runs the program as downloading reaches 100%, but while uTorrent is still either moving the file or seeding. See my bug report here.
A quick summary of the post, just in case that post gets deleted: you have to set the command in "Run this program when a torrent changes state:", add a %S parameter and check that %S == 11
4) Just a tip from my attempt at doing something very similar: when you set the variables from the arguments, add a tilde (%~1 instead of %1). This will strip the quotes off and let us more easily build command lines with the variables later.
You say that the log is not being written to. Try this as a test and see if it writes to the log.
If it doesn't there there is some other fundamental problem.
#echo off
title Liam's torrent-file script
rem Parameter usage: fromdir torrent-name label kind [filename]
rem corresponds to uTorrents flags: %D %N %L %K %F
echo *********************************************
echo Run on %date% at %time%
set "fromdir=%~1"
set "name=%~2"
set "label=%~3"
set "kind=%~4"
set "filename=%~5"
set "savepartition=F:\Completed Torrents"
set "winrar=C:\Program Files (x86)\WinRAR\WinRAR.exe"
set "torrentlog=F:\Torrent Scripts\logs\torrentlog.txt"
set "handledlog=F:\Torrent Scripts\logs\handled_torrents.txt"
set "errorlog=F:\Torrent Scripts\logs\ErrorLog.txt"
set "label_prefix="
set "handledlog=%userprofile%\desktop\handled_torrents.txt"
>> "%handledlog%" echo Input: "%fromdir%" "%name%" "%label%" "%kind%" "%filename%"
>> "%handledlog%" echo %date% at %time%: Handling "%label%" torrent "%name%"

Resources