Assist with batch file that searches and xcopy hidden file to specific dir - powershell

It's annoying to manually always search in the CMD and xcopy the hidden file, can someone whos good in scipting help me out?
I use these 2 commands:
Firstly i open CMD in the FOLDER2 and entering this command to find the hidden file in the hidden random sub dir:
dir /s /b | find "robotknow"
(robotknow is not the fullname of the file, only part of it.)
And then when it find the hidden file within the random made subdir i copy the whole path including the whole filename with the ending.
Xcopy /h *The whole path including the filename and ending* C:\hello
My folders:
$sourceDir = 'C:\Users\USER\AppData\Local\Packages\FOLDER1\FOLDER2'
$targetDir = 'C:\hello'
So i wish to create a batch that could search that string "robotknow" and copy the fullname of the file to my tagetdir.
Is it possible?
Im trying to learn commands but batching is harder, if i was unclear on anything please ask me thank you!
Edit:
I found few commands that could be useful but I dont know how to use them so that it works.
$searchStrings = For it to search after the string above i mentioned: "robotknow"
And
Copy-Item $_.FullName $targetpath
An example would be:
The filename has this in it's name "robotknow" and i want to copy it.
Copy the file im searching after to copy thats within the sub folder of the FOLDER2 which is an hidden random folder that i cannot se:
%LocalAppData%\Packages\FOLDER1\FOLDER2\THE-hidden-RANDOM-made-sub-DIR.
Copy it to it's final directory c:\hello
The final directory, simply just: c:\hello.
By hidden i mean that i cannot see in file explorer, windows GUI and neither if i put this simple command in CMD dir to show the hidden random folder where the file is located in, they are not showing.
The file only appears in CMD if i enter this command dir /s /b | find "robotknow" when im in the FOLDER2.
Only after that i can se the hidden random made dir/folder and the full hidden path to it (the file).

I suggest following batch file code for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=%LocalAppData%\Packages\FOLDER1\FOLDER2"
set "TargetFolder=C:\hello"
for /F "delims=" %%I in ('dir "%SourceFolder%\*robotknow*" /A-D /B /S 2^>nul') do %SystemRoot%\System32\xcopy.exe "%%~dpI*" "%TargetFolder%\" /C /E /H /K /Q /R /Y >nul
endlocal
The command FOR with option /F starts a separate command process with cmd.exe /C (more precisely %ComSpec% /C) in background to run the command line:
dir "C:\Users\{username}\AppData\Local\Packages\FOLDER1\FOLDER2\*robotknow*" /A-D /B /S 2>nul
DIR outputs to handle STDOUT of background command process
just the names of all files matching the wildcard pattern *robotknow* because of option /A-D (attribute not directory)
even on file having hidden attribute set because of using option /A and not excluding attribute hidden
in bare format because of option /B
with full qualified path because of option /S
found in specified directory or any subdirectory also because of option /S.
It is possible that DIR does not find any file system entry matching these criteria in which case it outputs an error message to handle STDERR. This error message is suppressed by redirecting it to device NUL.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
FOR with option /F captures all lines output to handle STDOUT of started command process and processes them line by line after started cmd.exe terminated itself.
FOR ignores empty lines which do not occur here. FOR ignores by default also all lines starting with a semicolon because of eol=; is the default for end of line character option. But a full qualified file name consisting of full file path, file name and file extension cannot start with ; and so default end of line option can be kept in this case. FOR splits up the lines by default into substrings with using normal space and horizontal tab character as string delimiters and assigns just first space/tab separated substring to specified loop variable. This line splitting behavior is not wanted here because of file path could contain a space character. For that reason option delims= is used to define an empty list of delimiters which disables the line splitting behavior.
So FOR assigns to specified and case-sensitive interpreted loop variable I the full qualified file name found and output by DIR and runs the command XCOPY.
XCOPY is executed with source being the full qualified path of found file referenced with %%~dpI always ending with a backslash concatenated with wildcard * and destination directory being specified target folder C:\hello.
The appended backslash at end of destination directory path makes it 100% clear for XCOPY that the destination is a directory and not a file which prevents the prompt if destination means a directory or a file. \ at end makes also usage of option /I unnecessary and XCOPY creates the entire destination directory structure if necessary.
The other XCOPY options are for really copying all files including files with hidden attribute set in directory containing the file matching the wildcard pattern *robotknow* with all subdirectories including empty subdirectories to destination directory with keeping attributes including read-only attribute.
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.
dir /?
echo /?
endlocal /?
set /?
setlocal /?
xcopy /?
See also the list of predefined Windows Environment Variables.

Related

How to take output of dir search and modify specified file

I'm trying to use this script to assist technicians with renaming files that are found on an end users computer within their %appdata% folder. The script works up until this point, but I can't figure out how to take the output of the DIR search to use it as the current directory so I can modify the destination folder.
Basically, I need to make changes to this folder:
C:\users\bob\appdata\local\apps\2.0\'7'\'7'\time...exe_bfe88f94fc69adaa_0005.0011_none_b883acbb6e8d0075
The two 7's or wildcards are always different folder directory names, so that's why I can't use a static path to make changes to these folders. Anyways, here is the script so far, it works just fine in locating the folder I need, but I cannot seem to use the output to specify it as the target so I can make changes to it. Thank you for your help.
cd %appdata%
cd ..
cd local\apps\2.0
dir "time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec" /ad /s
I've tried using the pipeline argument (|) and the '&' and then using a rename command or a removedir, but it cannot find the file specified.
Thank you for your help!
Here's a batch-file which is a little more direct than just recursing the entire tree. It only steps over the two 'unknown' directory names, (%%~nxG\%%~nxH), and checks there for the named directory, (which you should edit as needed on line 3):
#Echo Off & SetLocal EnableExtensions
Set "DirName=time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec"
Set "BaseDir=%LocalAppData%\apps\2.0"
Set "AppPath="
For /D %%G In ("%BaseDir%\*")Do For /D %%H In ("%%G\*")Do For %%I In (
"%%H\%DirName%")Do If "%%~aI" GEq "d" Set "AppPath=%%~I"
If Not Defined AppPath Echo %DirName% Not Found & Pause & Exit /B 1
Echo %%AppPath%% = %AppPath% & Pause
Nothing else should be modified except for the last line which I added just to provide some output, (you/your technicians would use "%AppPath%" to reference the target directory from that point forward).
If you were looking for something in powershell, then perhaps this will push you in the right direction:
$DirName = "time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec"
$AppPath = (RvPa "$Env:LocalAppData\apps\2.0\*\*\$DirName").Path
$AppPath
Once again the last line is just to provide output and show you the variable you'll need to reference your target directory, and the first line will need editing as needed.
This code uses a FOR loop to find directory names that match. There is an ECHO inside the loop since I do not know if multiple directories could be found.
#ECHO OFF
CD "%APPDATA%\.."
FOR /F "delims=" %%A IN ('DIR /S /B /A:D "time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec"') DO (
ECHO Found directory "%%~A"
SET THEDIR=%%~A
)
DIR "%THEDIR%"
REN "%THEDIR%\file1.txt" "file2.txt"

Find the most recently created file in the directories and sub-directories using PowerShell or Windows Batch

I have 30 different folders which I need to iterate thru, within each one there’s a Log folder and inside that, are the text files. I’m after the latest one, which I need to copy to the new location with the preferred name (E.G. 2020-03-28.txt.FolderServerName1, where appended variable FolderServerName1, identifies from which server it came from)
set source="\\ServerName\LogFolders"
set target=" C:\Data\CopiedLogFiles"
FolderServerName1
Log
2020-03-26.txt
2020-03-27.txt
**2020-03-28.txt**
FolderServerName2
Log
2020-03-26.txt
2020-03-27.txt
**2020-03-28.txt**
FolderServerName3
Log
2020-03-26.txt
2020-03-27.txt
**2020-03-28.txt**
https://devblogs.microsoft.com/oldnewthing/20120801-00/?p=6993
The post above is very useful, but I think I need another nested loop within, which I'm struggling with syntactically.
Thank You so much!
This file copying task can be done with:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("\\ServerName\LogFolders\*") do (
set "CopyDone="
for /F "delims=" %%J in ('dir "%%I\Log\20??-??-??.txt" /A-D-H /B /O-N 2^>nul') do if not defined CopyDone (
copy /Y "%%I\Log\%%J" "C:\Data\CopiedLogFiles\%%~nJ_%%~nxI%%~xJ" >nul
set "CopyDone=1"
)
)
endlocal
For each non-hidden subdirectory in \\ServerName\LogFolders the outer FOR loop first deletes the environment variable CopyDone and runs one more FOR loop.
The inner FOR loop starts in background one more command process using %ComSpec% /c and the command line enclosed in ' as additional commands. So executed with Windows installed into C:\Windows is in background for example:
C:\Windows\System32\cmd.exe /c dir "\\ServerName\LogFolders\FolderServerName1\Log\20??-??-??.txt" /A-D /B /O-N 2>nul
The command DIR searches in specified directory
only for non-hidden files because of option /A-D-H (attribute not directory and not hidden)
with a file name matching the wildcard pattern 20??-??-??.txt
and outputs in bare format because of option /B just each file name with extension without path
ordered reverse by name because of option /O-N
to handle STDOUT (standard output) of the background command process.
The reverse output sorted alphabetically by name results for the log file names that 2020-03-28.txt is output on first line, 2020-03-27.txt on second line and 2020-03-26.txt on third line.
It could be that the subdirectory Log does not exist at all or does not contain any file matching the wildcard pattern. In this case command DIR outputs an error message to handle STDERR (standard error) which is suppressed by redirecting it to device NUL with 2>nul.
Read the Microsoft article about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
The command process processing the batch file captures everything written to handle STDOUT of background command process and FOR processes this captured output line by line after started cmd.exe terminated itself.
FOR ignores empty lines which do not occur here.
FOR would split up by default each line into substrings using normal space and horizontal tab character as string delimiters, would next look if first substring starts with default end of line character ; in which case the line would be also ignored and otherwise would assign just first space/tab delimited string to specified loop variable. It would be possible here to use this default line processing behavior as the file names do not contain a space character. But it is nevertheless better to disable line splitting behavior by using delims= to define an empty list of string delimiters.
So the inner FOR assigns on first loop iteration the file name of newest file according to international formatted date in file name to loop variable J and runs the command IF.
On first loop iteration of the inner FOR loop the environment variable CopyDone is always not defined as made sure on the command line above and so the IF condition is true.
For that reason the file is copied which means for first folder FolderServerName1 that the executed COPY command is:
copy /Y "\\ServerName\LogFolders\FolderServerName1\Log\2020-03-28.txt" "C:\Data\CopiedLogFiles\2020-03-28_FolderServerName1.txt" >nul
The target file name is modified from requested 2020-03-28.txt.FolderServerName1 to 2020-03-28_FolderServerName1.txt. It is in general better to use a dot in the name of a file just once as separator between file name and file extension and keep the file extension at end of the name of the file to be able to open the file with a double click.
The environment variable CopyDone is defined with a value after the file copying is done without verification on success. The string value assigned to environment variable CopyDone does not matter in this case.
The inner FOR continues processing the captured lines by assigning one file name after the other to loop variable J and running the IF condition. But this condition is not true for any other file name than the first file name.
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.
copy /?
dir /?
echo /?
endlocal /?
for /?
if /?
set /?
setlocal /?

Find and replace text between certain characters with filename

Find and replace text between certain characters with filename, have about 100 files that require this so I'm thinking it needs a occurrence or something.
Original file name: test1.txt
Inside file replace the following two lines with the file name (inside each file the below strings might not be right after each other):
location000:/computer/[project]/name/123.php,32,1,2,512,0,,txt
newlocation000:/computer/[project]/name/123.php,32,1,2,512,0,,txt
Output in file test1.txt
location000:/computer/[project]/name/test1.php,32,1,2,512,0,,txt
newlocation000:/computer/[project]/name/test1.php,32,1,2,512,0,,txt
This is an easy to achieve task with using JREPL.BAT written by Dave Benham which is a batch file / JScript hybrid to run a regular expression replace on a file using JScript.
#echo off
if not exist "%~dp0jrepl.bat" (
echo ERROR: JREPL.BAT missing in directory "%~dp0".
echo/
pause
goto :EOF
)
for %%I in ("C:\Temp\*.txt") do call "%~dp0jrepl.bat" "^((?:new)?location000:/.+/).*(\.[^.,]+,)" "$1%%~nI$2" /F "%%I" /O -
This batch file works only on NTFS drives. It can result in an endless running loop on FAT16, FAT32 or ExFAT drives or skipping some text files. For a working solution independent on file system replace the last command line by:
for /F "eol=| delims=" %%I in ('dir "C:\Temp\*.txt" /A-D-H /B /ON 2^>nul') do call "%~dp0jrepl.bat" "^((?:new)?location000:/.+/).*(\.[^.,]+,)" "$1%%~nI$2" /F "C:\Temp\%%I" /O -
The batch file JREPL.BAT must be stored in same directory as the batch file with the code above. For that reason the batch file checks first if JREPL.BAT really exists in directory of the batch file and if this is not the case, outputs an error message, halts script execution to make it possible for a user to read that error message and then exits. See Where does GOTO :EOF return to?
The command FOR searches in specified directory C:\Temp for non hidden files matching the wildcard pattern *.txt and calls for each found text file the batch file JREPL.BAT to replace the file name between last / and first string starting with ., having one or more characters not being a dot or a comma with next character being a , (= file extension and comma) on lines starting case-sensitive with location000:/ or newlocation000:/ by the file name of the current *.txt file without file extension. So a file name in existing file can contain also one or more . in file name before file extension.
The solution working also on FAT drives uses command DIR to get a captured list of *.txt files with just file name and file extension without path and FOR processes this file names list line by line, i.e. file name by file name. So the list of *.txt files to process does not change on running FOR calling JREPL.BAT as it would be the case on using FOR directly to find the *.txt files on FAT drives.
NTFS returns a list of directory entries matching a wildcard pattern sorted alphabetically and so the list of *.txt files does not modify during FOR iterations in this case. But all FAT file systems return the list of directory entries matching a wildcard pattern according to last modification in directory with last modified file at end of the list. So while FOR gets one file name after the other on using for %%I in ("C:\Temp\*.txt") do from file system and processes the file with calling jrepl.bat which modifies the file, the file list changes on FAT drives and next directory entry returned to FOR on its search for *.txt is either the file just modified (= endless loop) or another file after skipping a file which should be also modified because of file list changed since last directory access by FOR.
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.
call /? ... explains also %~dp0 ... drive and path of argument 0 being the batch file itself.
dir /?
echo /?
for /?
goto /?
if /?
pause /?
jrepl.bat /?

removing directories with their path in txt file including space

I wanna remove directories that their path listed in a txt file. some of these paths include space. for example this is my txt file contents, named rd.txt:
D:\New folder\WOW
D:\New folder (2)\here I am
so I can't use this command in batch file:
for /d %%n in (rd.txt) do rd "%%n" /s /q
what command should I use?
for /F "delims=" %%n in (rd.txt) do rd "%%n" /s /q
It does the job.
Long story short (you can use for /? to see the parameters), delims indicates what delimiters should be used, and default contains space character, so setting delims to empty value seems to be what you need.

Command line to recursively delete files but excluding a certain file

I need to delete files of a certain type (.zip files, say) from a folder, and all of its sub-folders, using the command line. Ideally I am looking for something that can be run as a .bat file in Windows.
I know there is a /S switch for the DEL command to look in sub-folders, but to add to the challenge I need to exclude files of a certain name ("Backup.zip" as an example).
Is there a way to delete files recursively but exclude files of a certain name. It will not be practical in my situation to explicitly list all the file names I want to delete, only the files of the matching type I don't want to delete.
A nice trick: make the files you want to exclude read-only!
DEL /S will not delete read-only file.
The following script does not do exactly what you want (see my remarks below) but shows you how read-only files can be used to avoid deletion.
#ECHO OFF
:: This example supposes your first parameter is
:: the relative path to the folder to be deleted
:: and the second is the relative path (from the
:: the target folder) of the one to be excluded
:: Notice that this will only work if the folders
:: are in the working drive, if not, you ll
:: have to specify full paths
IF "%1"=="" GOTO ERROR
IF "%2"=="" GOTO ERROR
IF NOT EXIST %1\NUL GOTO ERROR
CD %1
IF NOT EXIST %2\NUL GOTO ERROR
ECHO Starting up the deletion process
ECHO. * Setting attributes
attrib %1\*.mp3 -r -s -h > NUL
attrib %2\*.mp3 +r > NUL
ECHO. * Deleting files
del /s %1\*.mp3
ECHO. * Reseting attributes
attrib %2\*.mp3 -r > NUL
ECHO.
ECHO Operation completed!
ECHO.
GOTO END
:ERROR
ECHO Parameters:
ECHO. Param1 -> target folder
ECHO. Param2 -> folder to be ignored
ECHO.
GOTO END
:END
Note: you can adapt this script in order to ignore not just a sub-folder but all files of given type:
attrib /S *.xxx +r > NUL
will in effect help you to exclude all 'xxx' files of the current directory and all sub-directories (hence the /S option).
Note: the "> NUL" part is a redirection often used to hide standard output, instead of displaying it on screen.
It can be dangerous if used too often (in a large loop with different paths involved, for instance) since it is a device, and like all devices (AUX, COMn, LPTn, NUL and PRN):
opening a device will claim one file handle. However, unlike files, devices will never be closed until reboot.
each device exists in every directory on every drive, so if you used redirection to NUL in, say, C:\ and after that you use it again in C:\TEMP, you'll lose another file handle.
Just do this, easy
windows button + r
type cmd and hit enter
Navigate to parent directory:
type c: or d: (or letter of the drive you want to navigate to)
type dir to see a list of that directory's contents ( dir /ah to see hidden files )
then to change directory, type cd xxxx ( xxxx = directory name )
Repeat 4&5 until you get to the directory where you want to run the batch delete
then type your pattern. Something like: del /S /ah *.jpg and hit enter. It will run through all sub-directories, and remove all visible and hidden files that are .jpg files
* is a wildcard
/S deletes from all subfolders
/ah a = select files based on attribute, h = hidden
Example: to delete those annoying .DS_Store files that appear when you copy from Mac to Windows, run:
del /S /ah .DS_Store
or
del /S /ah ._*
which will get all the 'duplicate' hidden files that are also created when copying from Mac to Windows.
You can easily loop a set of files and perform a command on each one, like this:
set match=D:\blah\M*.zip
for %%x in (%match%) do (
del %%x
)
Then I think you need to read this article on how to manipulate strings in DOS:
http://www.dostips.com/DtTipsStringManipulation.php
You can simply use below:
forfiles /p C:\temp-new /s /c "cmd /c if #isdir==FALSE del #file"
TechNet Referenceenter link description here
Perhaps the 'forfiles' command could be of use
http://technet.microsoft.com/en-us/library/cc753551.aspx
Hope that helps.
This script will delete all .zip files from a folder (and subfolders), BUT ONLY IF the file name does not contain the word "backup", or "Backup" or "BACKUP", etc.
# Script DeleteZip.txt
var str folder, filelist, file
cd $folder
lf -r -n "*.zip" > $filelist
while ($filelist <> "")
do
lex "1" $filelist > $file
# Does this $file contain the word "backup" ? Do case independent search (-c option).
if ( { sen -c "^backup^" $file } <= 0 )
system del ("\""+$file+"\"")
endif
done
Script is in biterscripting ( http://www.biterscripting.com ). Save the script in file C:/Scripts/DeleteZip.txt. Run the script as
script "C:/Scripts/DeleteZip.txt" folder("C:/testfolder")
Will do the delete operation on folder C:/testfolder and all its subfolders, at all levels.
A simple way that you need:
FORFILES /P "DIRECTORY" /S /M SEARCHMASK /C "cmd /c if #file neq \"FILE_TO_EXCLUDE\" del /f #file"
You still can adapt the command to your need to exclude specific files and/or by date. More details in the 'forfiles' documentation below.
https://learn.microsoft.com/pt-br/windows-server/administration/windows-commands/forfiles