So we are running a backup script for my job and until now they just had the script pull the computer name and use that as the folder it creates. The problem that we are encountering is that when we go to then use the restore script it becomes useless.
Our computer names are for example SMITHT#-Year-A.
But I would like the batch script to not use the whole name because often this is used when we change the year of the computer. And because sometimes there are numbers after a persons name there are variying lengths so most of the knowledge I have on deciding start and stop points is coming up useless.
Is there a way to have the batch create a folder using the %COMPUTERNAME% function telling it to stop at the "-" so all we get is the name and number of the person?
To split a string at a certain character use for /F:
for /F "tokens=1 delims=- eol=-" %L in ("%COMPUTERNAME%") do (set SHORTNAME=%L)
This command line stores the string portion before the (first) - into variable SHORTNAME.
For details type for /? in the console window.
To use the above line in a batch script, replace %L by %%L.
Related
I have a batch script that needs to run as admin. I will be distributing to users so it would be best if they can run it from Windows Explorer.
Unfortunately, it doesn't work when run from explorer (right click -> run as admin). It does work when called from a pre-existing admin terminal.
Initially I thought the problem was with the active directory, but I added a "cd /d %~dp0" as the first command. I confirmed through echo that this places them both in the same directory, but it still fails when running from explorer.
The failure occurs when reading an external file in the same directory as the .bat. It pulls empty strings when run from explorer. Here is sample code:
rem Make sure active directory is correct (verified that this works)
cd /d %~dp0
rem Load parameters from params.txt
for /f "delims== tokens=1,2" %%G in ("params.txt") do set %%G=%%H
rem Print params (it's a loop so you can read it when running from expl.)
for /l %%a in (1 1 100000) do echo %DST%
Then you just need to make sure params.txt is in same directory as .bat and includes the line "DST=some\directory\name"
Anybody know why this doesn't work?
As has been pointed about by #nephi12 in his answer if your file name does not have spaces you can remove the quotes, otherwise it thinks the IN clause is a string you want to parse. If you need to quote your file names then you need to use the USEBACKQ option as pointed out by the comments. Once you use that option your code works just fine.
But I would like to make a point with your code. If the contents of your params.txt file is:
"DST=some\directory\name"
Then your FOR command can just be this:
for /f "usebackq tokens=1 delims=" %%G in ("params.txt") do set %%G
I am not understanding why you are echoing the %dst% variable 100,000 times?
For one thing, take away the "s from around params.txt as double-quotes means string parsing, while unquoted is a list of files.
Second, try prepending params.txt with %~pd0\ to ensure the correct path, rather than changing directory.
Similar question to these have been tons of time but, for what i want it is something different. I have tried searching but, not what I want.
Now I have certain (.txt) files in my folder (hidden-files) where certain text files (Multiple text files) are stored which have special characters (%!=^";#% ..etc) in them I would like to remove these special characters and replace them with (-) in a rename loop so the file(s) will be renamed.
Code (Got it from here somewhere) Edited to my use but, it didn't worked.
for /f "delims=" %%a in ('dir "%~dp0hidden-files\*.txt"') do (set "newname=%~nx1"
set "newname=%newname:!=-%"
set "newname=%newname:_=-%"
set "newname=%newname:==-%"
set "newname=%newname:%=-%"
echo ren "%%a" "!newname!")
Would appreciate any help. Cheers.
You have a whole host of problems with your code. I'm too tired to list them all, but there is one issue that is extremely difficult to solve with pure batch - there is no simple way to replace an = literal within a string using batch. The simplest (and perhaps most effective) way to accomplish this is to look character by character for the = and replace it via substring operations.
There are a bunch of other issues that require advanced batch techniques to solve.
I have a much simpler solution for you - my JREN.BAT utility uses regular expression replacement to rename files. It is a hybrid JScript/batch script that runs natively on any Windows machine from XP onward. Use jren /? from the command line to access the built-in help. You might want to use jren /? | more to see one screen at a time. I never use MORE because my console is configured with a large buffer that lets me scroll up to see past output.
Once you have JREN.BAT on your machine, preferably in a folder that is within your PATH variable, then all you need is the following to rename the files within the current directory - no additional batch script required:
jren "[!_=%]" "-" /fm *.txt
If needed, you can specify the folder as an option:
jren "[!_=%]" "-" /fm *.txt /p "c:\YourPathHere"
If you put the command within another batch script, then you will need to use CALL JREN, and the percent needs to be double escaped as %%%%. Percent literals must be escaped as %% within batch files, and the CALL requires an extra round of escape:
#echo off
call jren "[!_=%%%%]" "-" /fm *.txt /p "%~dp0hidden-files"
Update in response to comment
Adding (, ), [, and ] to the list of characters to replace is simple. The only trick is you must escape the ] as \] when it appears within a character set [....].
#echo off
call jren "[!_=%%%%[\]()]" "-" /fm *.txt /p "%~dp0hidden-files"
The other option is to place the ] immediately after the opening [.
#echo off
call jren "[]!_=%%%%[()]" "-" /fm *.txt /p "%~dp0hidden-files"
Regular expressions are incredibly powerful, but they can be confusing to the uninitiated. Use jren /?regex to access Microsoft's help page on all the supported regular expression syntax. There are loads of tutorials available on the internet, as well as web sites that allow you to conveniently test out regular expressions.
If you are developing a JREN command, I suggest you first use the /t option to test it out without actually renaming anything.
Last update for question in comment
File names cannot contain *, ?, |, <, >, \, /, : or ", so you don't need to worry about those characters. I'm not sure what you did, but I don't see the enclosing [...] to represent a character set. The following should work fine:
call jren "[`~!##$%%%%^&_ +=,';}{[\]()]" "-" /fm *.txt /p "%~dp0hidden-files"
I'm creating then zipping a file that is stamped with the current date with 7-zip. I am able to use the following switch to create the zip file to add to:
7z -tzi C:\RACHAEL\my_work\dbs\MyDb\%DATE:~11,4%\%DATE:~5,2%\MyDb_bak_%DATE:~11,4%-%DATE:~5,2%-%DATE:~8,2%.bak.zip
but adding the "-i!" command does not locate the file specfied
7z -tzi C:\RACHAEL\my_work\dbs\MyDb\%DATE:~11,4%\%DATE:~5,2%\MyDb_bak_%DATE:~11,4%-%DATE:~5,2%-%DATE:~8,2%.bak.zip -i!C:\RACHAEL\my_work\dbs\MyDb_bak_<get_current_date_in_correct_format>.bak
How would one achieve locating the file in this directory containing the current formatted date from a batch file? Is there an escape character? The '%' does not provide this purpose in 7zip, which I assumed it would.
Thanks in advance!
forfiles /d +0 /c "cmd /c echo #path"
See forfiles /?
Format of date string of environment variable DATE depends on language settings of Windows.
Executing a batch file with the 2 lines below on German Windows XP
#echo %DATE%
#echo %DATE:~6,4%-%DATE:~5,2%-%DATE:~8,2%
results in output
16.08.2014
-.2-14
This is not a valid date string in format YYYY-MM-DD as you want obviously in your command.
I needed to change the second line to
#echo %DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%
to get output on running the batch file in a command prompt window
16.08.2014
2014-08-16
Explanation for above date string with substring extraction:
%DATE:~6,4% ... extracts from string of environment variable DATE four characters beginning from seventh character. First character has character index 0.
%DATE:~3,2% ... extracts from string of environment variable DATE two characters beginning from fourth character.
%DATE:~0,2% ... extracts from string of environment variable DATE two characters beginning from first character.
Now you know what the date substring extraction code in your commands do. And you can see also how to verify output of substring extraction code using a small batch file executed from within a command prompt window, or from Windows Explorer after appending a third line with command pause to see the output.
This should help you to find the correct code for date string building on your computer according to requested date format depending on date string format of environment variable DATE.
Character ! has a special meaning in batch files as it is used for referencing the value of an environment variable with delayed expansion. To get it interpreted as literal character in a batch file, it must be escaped with ^ which means putting left to ! the character ^ resulting in ^!.
Therefore the command
7z.exe a -tzip C:\RACHAEL\my_work\dbs\MyDb\%DATE:~11,4%\%DATE:~5,2%\MyDb_bak_%DATE:~11,4%-%DATE:~5,2%-%DATE:~8,2%.bak.zip -i^!C:\RACHAEL\my_work\dbs\MyDb_bak_%DATE:~11,4%-%DATE:~5,2%-%DATE:~8,2%.bak
might the right one in a batch file on your computer.
But on German Windows XP the right command is:
7z.exe a -tzip C:\RACHAEL\my_work\dbs\MyDb\%DATE:~6,4%\%DATE:~3,2%\MyDb_bak_%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%.bak.zip -i^!C:\RACHAEL\my_work\dbs\MyDb_bak_%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%.bak
One laste note: In batch file it is often better to specify executables with full path. Therefore it is better here to specify not just 7x.exe, but something like "C:\Program Files\7-Zip\7z.exe". The path to 7x.exe may be different on your computer.
was missing the escape character ^ before the path I was trying to add to the successfully zipped directory created with 7zip.
This is the corrected statement:
echo Using 7-zip to compress today's backup folder...
7z a -tzip C:\RACHAEL\my_work\dbs\MyDb\%DATE:~11,4%\%DATE:~5,2%\MyDb_bak_%DATE:~11,4%-%DATE:~5,2%-%DATE:~8,2%.bak.zip -i!^C:\RACHAEL\my_work\dbs\MyDb\%DATE:~11,4%\%DATE:~5,2%\MyDb_bak_%DATE:~11,4%-%DATE:~5,2%-%DATE:~8,2%.bak
^missing escape character right here so that path could actually be parsed per date format.
I want to assign the output of running a batch script with arguments to a variable. Please suggest me on how to do this.
Example:
The output of datemath.bat %Date_Pattern% - 2 should be assigned to a variable.
Say my date_pattern was 2013 05 03 then my variable will come up with 2013 05 01
There are generally two ways to store the output of a command into a variable. I'm going to assume there is only one line of output to be captured. I'm also assuming the output is on stdout, and not stderr. The command could be a call to a batch file, a call to a subroutine within a batch file, an internal command, a standard external command (executable), or a 3rd party executable - the process for capturing the output into a variable is the same.
1) Redirect the output to a temporary file, and then read the value into a variable using SET /P
call dateMath.bat %Date_Pattern% - 2 >output.tmp
<output.tmp set /p "result="
del output.tmp
Typically the temporary file is created in the %TEMP% folder, but I kept everything in the current directory just for simplicity.
People generally like to avoid temporary files if possible, although sometimes that is the best option.
2) Use FOR /F to capture the output directly, without using a temporary file. FOR /F is a complicated command with many options. It is designed to parse input into delimited tokens. The default delimiter is a space; but you want the entire string to be captured in one variable. So you need to set the delimiter to nothing. FOR /F can read file contents, a string, or command output. You want command output, so the IN() clause should be enclosed in single quotes. The # symbol is used to suppress echoing of the SET command line.
for /f "delims=" %A in ('dateMath.bat %Date_Pattern% - 2') do #set "result=%A"
If you want to use the above command in a batch script, then the FOR variable percents need to be doubled. Your script probably has echo off, so # is not needed.
for /f "delims=" %%A in ('dateMath.bat %Date_Pattern% - 2') do set "result=%%A"
There is an entirely different approach you could take: modify your batch script to optionally store the result directly in the variable. You should read the following excellent tutorial from DosTips.com DOS Batch - Function Tutorial The site constantly refers to DOS, but in reality it is a site that specializes in all things dealing with Windows batch scripting.
I'm trying to create a batch file (via Windows XP Pro) that copies 2 files (.zpl) who's filename's vary in length. ZPL files relate to label printer code. File names are as follows:
FillXferDataPBHAMFill###########.zpl
FillFormatsPBHAMFill############.zpl
The pound signs represent a number associated with a particular label/job to be printed. These numbers are identical per job. From one job to the next the numbers vary in length and always change. The directory I'm trying to pull these from contains ZPL files from multiple locations, however, I just want the BHAM ones.
The batch will copy from: \Server\C:\Directory1\Directory2\Directory3
To be copied to: \Server\Directory1\Directory2
Not sure if this will complicate things further, but the batch file will be ran from a 3rd machine. Furthermore, I do not need to copy every file everytime. Whenever new print jobs are sent, supervisors will run the batch to copy the new print jobs within the last X amount of time. X being minutes. Here is what I have so far...
#echo off
SETLOCAL enableExtensions enableDelayedExpansion
SET sourceDir=Server\C:\Directory1\Directory2\Directory3
SET targetDir=Server\Directory1\Directory2
FOR %%a (FillFormatsPBHAM*.bat) DO (
SET "filename=%%a"
SET "folder=%targetDir%"
XCOPY "%%a" !folder!
)
FOR %%b (FillXferDataPBHAM*.bat) DO (
SET "filename=%%b"
SET "folder=%targetDir%"
XCOPY "%%b" !folder!
)
:END
I apologize for a lengthy post; just wanting to be as thorough as possible. I'm learning this on the fly so bare with any ignorance on my part. Thank you in advance for ANY help!!
StackOverFlow Material Reviewed: Reference1, Reference2 -- I've been looking everywhere over the past week and these were the 2 most helpful so far.
I see some ways to fix or improve your BAT script.
The FOR command syntax is FOR %%a IN (*.bat) DO (
The sourcedir variable is set Server\C:\Directory1\Directory2\Directory3, which is not a correct path in Windows.
you initialize but don't use %sourcedir% variabe neither in your FOR loop nor in your copy commnand
you should either change the current drive and dir with a pushd %sourcedir% command, or specifying it in the FOR command.
your FOR loop assigns a %filename% variable that is never used, you may skip this assignment.
you FOR loop assigns a %folder% variable that is only then used in the copy command, you can skip this assignment and simply use %targetdir%
but, to just copy all files from one folder to the other you don't need FOR to iterate over all of them, you might just copy them right.
So, take a look at this simple script to get you started..
SET sourceDir=\\servername\sharename\Directory1\Directory2\Directory3
SET targetDir=\\anotherserver\sharename\Directory1\Directory2
xcopy %sourceDir%\FillFormatsPBHAM*.bat %targetDir%
xcopy %sourceDir%\FillXferDataPBHAM*.bat %targetDir%