Batchfile to create backup and rename with timestamp - windows

I have the following network path to copy the file to an archive folder. It copies File 1 from Folder to Archive but I would like to add these 2 adjustments that won't work.
Rename File 1-1 to File 1 - date + time
Running it now displays a cmd box with the copy code, is it possible
to run it in the background or have a loading screen to show the
progress?
For my code I followed this example to change the name to a date.
copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1-1.xlsx"
/f "tokens=1-5 delim s=/ " %%d in ("%date%") do rename "F:\Folder example 2.xlsx" "F:\Folder\File example %%e-%%f-%%g.xlsx"

try this:
ren "File 1-1" "File 1 - %date:/=-% %time::=-%"

See if this is what you want to do:
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"

I've modified Foxidrive's answer to copy entire folders and all their contents.
this script will create a folder and backup another folder's contents into it, including any subfolders underneath.
If you put this in say an hourly scheduled task you need to be careful as you could fill up your drive quickly with copies of your original folder. Before bitbucket etc i was using as similar script to save my code offline.
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=YourPrefixHere_%YYYY%%MM%%DD%#%HH%%Min%
rem you could for example want to create a folder in Gdrive and save backup there
cd C:\YourGoogleDriveFolder
mkdir %stamp%
cd %stamp%
xcopy C:\FolderWithDataToBackup\*.* /s

Renames all .pdf files based on current system date. For example a file named Gross Profit.pdf is renamed to Gross Profit 2014-07-31.pdf. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf.
You could replace the ? with the report name Gross Profit, but it will only rename the one report. The ? renames everything in the Conduit folder. The reason there are so many ?, is that some .pdfs have long names. If you just put 12 ?s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?, then try it with many ?s. The ? length should be a little longer or as long as the longest report name.
#ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.
You can also run your batch script through a vbs script like this:
'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True
This will execute your batch file with no cmd window shown.

Related

Batch script to fetch and play specific video file

I am having trouble with creating a batch file which then can be mapped to a keyboard shortcut, The basic's of the script is it asks for the season, episode and shot and finds it via that input in the directory however I having trouble with the fact that some folders have specific names at the end and I cant understand how to go about creating wild cards.
#echo off
set /p Series=Series:
set /p Episode=Episode:
set Series=00%Series%
set Episode=00000%Episode%
set Episode=%Episode:~-3%
rem open up review
set Path="P:\projectName\06_review\series_%Series%\sr%Series%_ep_%Episode%"
for /f "tokens=*" %%a in ('dir /A:-D /B /O:-D /S %Path%') do set NEW=%%a&& goto:n
:n
start %NEW%
So far this is doing well grabbing the latest file but once it needs to grab a folder that has more characters after \sr%Series%_ep_%Episode% it fails, but what is the best way to create wild cards for any possible string after the matching input?

different behaviors of WMIC in command line and windows explorer

My conundrum is related to the q/a thread at the following link: How to append date to directory path in xcopy
I'm new to this forum, and I had the same kind of question, and I'm using Windows 10, so I used the answer given in that thread by foxidrive about how to use WMIC for this, and it works fabulously, except for one issue that I've not yet figured out...
I modified the script that foxidrive provided, as follows:
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set datestamp=%dt:~0,8%
set timestamp=%dt:~8,6%
set YYYY=%dt:~0,2%
set YY=%dt:~2,2%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
for /f "tokens=%dow%" %%a in ("Su Mo Tu We Th Fr Sa") do set day=%%a
set stamp=%YY%%MM%%DD%%HH%%Min%%day%
REM echo Today is %day%.
md "%stamp%MoreDirName"
xcopy %source% /E /y .\"%stamp%MoreDirName"
When I run the batch file from cmd.exe, I get the desired result, namely, a directory is created with the date format the way I want it, and the date and time stamp that I want includes the name of the day of the week. However, when I double-click on the batch file in windows explorer, the folder is created and folders/files are copied, but the name of the day of the week does not appear in the new folder name. I am confused by this behavior and I would like to know how to override it, please.
I would have researched the issue more, but I am not sure what to search for other than ``different behaviors of WMIC in command line and windows'', and such a search yielded no helpful results. But since my efforts were based specifically upon the referenced stack exchange q/a thread, it seems to me that this is an appropriate place to document this strange behavior and get explanations if possible, which might help me, and others later, to compose better script.
I am confused by this behavior and I would like to know how to override it
There is no problem with wmic. The Issue is with your batch file, which contains two undefined variables).
for /f "tokens=%dow%" %%a in ("Su Mo Tu We Th Fr Sa") do set day=%%a
You don't set dow anywhere in your batch file.
xcopy %source% /E /y .\"%stamp%MoreDirName"
You also don't set source anywhere in your batch file.
What probably happened:
You have dow and source hanging about in your cmd environment from another batch file you have run that does not include the setlocal command (which prevents variables leaking into the parent cmd shell).
That means:
The batch file run from a cmd shell will work if dow and source are set in that instance of cmd.
The batch run from explorer won't work because it start a new instance of the cmd shell and dow and source are undefined.
Corrected batch file:
Here is a modified version of your batch file that will work when run from a cmd shell or from explorer, and correctly sets up Day of the Week.
rem #echo off
setlocal
set source=SomeSourceValue
rem use findstr to strip blank lines from wmic output
for /f "usebackq skip=1 tokens=1-6" %%g in (`wmic Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year ^| findstr /r /v "^$"`) do (
set _day=00%%g
set _hours=00%%h
set _minutes=00%%i
set _month=00%%j
set _seconds=00%%k
set _year=%%l
)
rem pad with leading zeros
set _month=%_month:~-2%
set _day=%_day:~-2%
set _hh=%_hours:~-2%
set _mm=%_minutes:~-2%
set _ss=%_seconds:~-2%
rem get day of the week
for /f %%k in ('powershell ^(get-date^).DayOfWeek') do (
set _dow=%%k
)
set _stamp=%_year%%_month%%_day%%_hh%%_mm%%_dow:~0,2%
md "%_stamp%MoreDirName"
xcopy %source% /E /y .\"%_stamp%MoreDirName"
endlocal
Notes:
The batch file uses a more elegant way to retrieve the timestamp components from wmic.
Modify the above as appropriate to set source correctly.
Credits:
Thanks to Danny Beckett for this answer which provided the PowerShell weekday trick.
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
for /f - Loop command against the results of another command.
getdate - Display the date and time independent of OS Locale, Language or the users chosen date format (Control Panel/Regional).
setlocal - Set options to control the visibility of environment variables in a batch file.
variables - Extract part of a variable (substring).
wmic - Windows Management Instrumentation Command.

Batch copy files from different folders based on Date LOOP

I hope someone can help me.
Suppose you have the following folder:
(Where YYYYMMDD indicates the folder name)
C:\folder\20160101
C:\folder\20160102
C:\folder\20160203
... until the
C:\folder\20160231
Inside the folders are there any file sort by code for example:
XXX0001
XXX0002
XXX0003
I would like to create a batch file that according to three manually set variables
CODE: XXX0001
DATA FROM = for example 20160101
DATE UP = for example 20160131
I want to move all files with the dates entered from Folder Input to Folder Output.
I created a good part of the script, but I'm stuck for the loop.
How can I do?
#echo off
setlocal enabledelayedexpansion
cls
set CODICE=
set /P CODICE=Insert code: %=%
set DATADA=
set /P DATADA=Insert Date[AAAAMMGG es (20160303)]: %=%
set DATAFINE=
set /P DATAFINE=Insert Data [AAAAMMGG es (20160306)]: %=%
set /A DATASOTTR=%DATAFINE%-%DATADA%
FOR /L %%i IN (0,1,%DATASOTTR%) DO (..... AND NOW??)
REM copy /-y \input\%DATA%\%CODICE% c:\output

batch file to move and rename folder to a relative path

I have the following batch file in Windows 7 to be executed by a context menu shortcut. My aim is to move and rename a quote folder containing subfolders and files to a different path and rename it with the project number inserted when prompted.
for %%Q in (.) do set quotenumber=%%~nQ
for %%Y in (.\..) do set year=%%~nY
for %%C in (.\..\..\..) do set client=%%~nC
set /P projectnumber="Enter Project number>"
move "c:\myfiles\mainfiles\clients\%client%\quotes\%year%\%quotenumber%" "c:\myfiles\mainfiles\clients\%client%\projects\%year%\%projectnumber%"
I get the error "the process does not have access to the file because it is being used by another process".
Can anybody tell me what I am doing wrong? I am not a programmer and cannot get this to work!
Any help would be greatly appreciated.
Looking at your code I'm assuming that you;re executing it in c:\myfiles\mainfiles\clients\%client%\quotes\%year%\%quotenumber% dir.
And in the last line you try to move the same dir to another place.Which is impossible because the dir is held by the script itself.Try this:
for %%Q in (.) do set quotenumber=%%~nQ
for %%Y in (.\..) do set year=%%~nY
for %%C in (.\..\..\..) do set client=%%~nC
set /P projectnumber="Enter Project number>"
cd ..
move "c:\myfiles\mainfiles\clients\%client%\quotes\%year%\%quotenumber%" "c:\myfiles\mainfiles\clients\%client%\projects\%year%\%projectnumber%"

How to create a folder with name as current date in batch (.bat) files

I don't know much about windows .bat file syntax. My simple requirement is to create a folder at a specific location with name as current date. I tried searching this on google but didn't get any good option. Is there any way to do this?
mkdir %date:~-4,4%%date:~-10,2%%date:~7,2%
Quick and dirty: If you can live with the date being UTC instead of local, you can use:
for /f "skip=1" %%d in ('wmic os get localdatetime') do if not defined mydate set mydate=%%d
md %mydate:~0,8%
Works in all locales. Only on XP and higher, though.
Try this (an equivalent of bash backquotes):
for /f "tokens=1* delims=" %%a in ('date /T') do set datestr=%%a
mkdir %datestr%
For further information, see http://ss64.com/nt/for_cmd.html
You need to get rid of the '/' characters in the date before you can use it in mkdir like this:
setlocal enableextensions
set name=%DATE:/=_%
mkdir %name%
If you want mm-dd-yyyy format you can use:
mkdir %date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%
This depends on the regional settings of the computer, so first check the output of the date using the command prompt or by doing an echo of date.
To do so, create a batch file and add the below content
echo %date%
pause
It produces an output, in my case it shows Fri 05/06/2015.
Now we need to get rid of the slash (/)
For that include the below code in the batch file.
set temp=%DATE:/=%
if you echo the "temp", you can see the date without the slash in it.
Now all you need to do is formatting the date in the way you want.
For example I need the date in the format of YYYYMMDD, then I need to set the dirname as below
To explain how this works, we need to compare the value of temp
Fri 05062015.
now position each characters with numbers starting with 0.
Fri 0506201 5
01234567891011
So for the date format which I need is 20150605,
The Year 2015, in which 2 is in the 8th position, so from 8th position till 4 places, it will make 2015.
The month 06, in which 0 is in the 6th position, so from 6th position till 2 places, it will make 06.
The day 05, in which 0 is in the 4th position, so from 4th position till 2 places, it will make 05.
So finally to set up the final format, we have the below.
SET dirname="%temp:~8,4%%temp:~6,2%%temp:~4,2%"
To enhance this date format with "-" or "_" in between the date, month and year , you can modify with below
SET dirname="%temp:~8,4%-%temp:~6,2%-%temp:~4,2%"
or
SET dirname="%temp:~8,4%_%temp:~6,2%_%temp:~4,2%"
So the final batch code will be
======================================================
#echo off
set temp=%DATE:/=%
set dirname="%temp:~8,4%%temp:~6,2%%temp:~4,2%"
mkdir %dirname%
======================================================
The directory will be created at the place where this batch executes.
echo var D = new Date() > tmp.js
echo D = (D.getFullYear()*100+D.getMonth()+1)*100+D.getDate() >> tmp.js
echo WScript.Echo( 'set YYYYMMDD='+D ) >> tmp.js
echo #echo off > tmp.bat
cscript //nologo tmp.js >> tmp.bat
call tmp.bat
mkdir %YYYYMMDD%
I had a problem with this because my server ABSOLUTELY had to have its date in MM/dd/yyyy format, while I wanted the directory to be in YYYY-MM-DD format for neatness sake. Here's how to get it in YYYY-MM-DD format, no matter what your regional settings are set as.
Find out what gets displayed when you use %DATE%:
From a command prompt type:
ECHO %DATE%
Mine came out 03/06/2013 (as in 6th March 2013)
Therefore, to get a directory name as 2013-03-06, code this into your batch file:
SET dirname="%date:~6,4%-%date:~0,2%-%date:~3,2%"
mkdir %dirname%
for /F “tokens=1-4 delims=/ ” %%A in (‘date /t’) do (
set DateDay=%%A
set DateMonth=%%B
set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
md %CurrentDate%
This will give you a newly created folder with today’s date, in the format of DD-MM-YY
Sourced from: Ali's Knowledge Base
This should work:
mkdir %date%
If it doesn't, try this:
setlocal enableextensions
mkdir %date%
this is a more simpler solution.
#ECHO OFF
set name=%date%
echo %name%
mkdir %name%
I am sitting in exactly the same boat as you as soon as i am AM before 10 i cannot use the below, i have set my time from 12hr to 24 hr, changed hh/mm to HH/mm I have tried most of the codes i could find. below will help at least a little. tweak and fix :)
Below may help also
set DD=%DATE:~0,2%
set MM=%DATE:~3,2%
set YY=%DATE:~8,2%
set YYYY=%DATE:~6,4%
set hh=%hh: =0%
set mm=%TIME:~3,2%
if "%time:~0,1%" == " " (set folderdate=0%time:~1,1%) ELSE set folderdate=%time:~0,2%
mkdir folderdate=%date:~6%%date:~3,2%%date:~0,2%_%folderdate%%time:~3,2%
copy \Makereport*.CSV \Makereport\%folderdate%\
cd %folderdate%
REM -( 7zip in c:\batch)
Path = c:\batch
7z a Retail.zip *.CSV -pRetailPassword
cd..
del *.csv
the expression %date:~p,n% returns n number of characters from position p in the date string.
if my system date string is Mon23/11/2015
the command
%date:~1,3%
returns the value
Mon
the command
%date:~10,4%
returns the value
2015
and in conjunction with the md (or mkdir) command
the command
md %date:~10,4%%date:~7,2%%date:~4,2%
makes a directory named
20151123
likewise if your date string in in the format
Monday, 23/Nov/2015
the command
md %date:~16,4%%date:~12,3%%date:~9,2%
makes a directory named
2015Nov23
If you accidentally return characters from the date string that are not allowed in folder names or use invalid values for p and n you will get an error.
Additionally if you return values that include \ this may create a folder within a folder.
If your locale has date format "DDMMYYYY" you'll have to set it this way:
set datestr=%date:~-4,4%%date:~3,2%%date:~-10,2%
mkdir %datestr%
This works for me, try:
ECHO %DATE:~7,2%_%DATE:~4,2%_%DATE:~12,2%
Thanks for the info all, very helpful. I needed something that could create "backup" folder as often as every minute in the same directory, as well as call on it later in the script. Here's what I came up with:
# echo off
CD %userprofile%\desktop
SET Datefolder="%DATE:~4,2%-%DATE:~7,2%-%DATE:~12,2%_%time:~1,1%%time:~3,2%"
MD "%Datefolder%"
This gives me a folder on the currently logged on user's desktop named: mm-dd-yy_hmm (hour minute minute) ie: 07-28-15_719
You'll like this, change it so that it can suit your requirements.
mkdir today
Copy Desktop\test1\*.* today
setlocal enableextensions
set name=%DATE:/=_%
Rename "today" _OlddatabaseBackup_"%name%"
Use this batch script made by me:
#echo off
title Folder Creator
color b
setlocal enabledelayedexpansion
echo Enter the folder name, you can use these codes:
echo /t - Time (eg. 16:29)
echo /d - Date (eg. 17-02-19)
echo /a - Day (eg. 17)
echo /m - Month (eg. 02)
echo /y - Year (eg. 19)
echo /f - Full Year (eg. 2019)
echo.
set /p foldername=Folder Name:
set foldername=%foldername:/t=!time:~0,5!%
set foldername=%foldername:/d=!date:~0,2!-!date:~3,2!-!date:~8,2!%
set foldername=%foldername:/a=!date:~0,2!%
set foldername=%foldername:/m=!date:~3,2!%
set foldername=%foldername:/y=!date:~8,2!%
set foldername=%foldername:/f=!date:~6,4!%
md %foldername%
For example if you wanted to make a folder named the date in the DD-MM-YY format you would type "/d" but if you wanted to do that in the DD-MM-YYYY format you would type "/a-/m-/f".
I use the next code to make a file copy (e.g. test.txt) before replacing:
cd /d %~dp0
set backupDir=%date:~7,2%-%date:~-10,2%-%date:~-2,2%_%time:~0,2%.%time:~3,2%.%time:~6,2%
echo make dir %backupDir% ...
md "%backupDir%"
copy test.txt %backupDir%
It creates directory in format DD-MM-YY_HH.MM.SS and places text.txt there.
Time with seconds in the name is necessary to create directory without additional verification.
https://stackoverflow.com/a/31789045/1010918 foxidrive's answer helped me get the folder with the date and time I wanted. I would like to share this method here since it worked great for me and I think it could help other people too, regardless of their locale.
rem The four lines below will give you reliable YY DD MM YYYY HH Min Sec MS variables in XP Pro and higher.
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "dirname=%YYYY%-%MM%-%DD% %HH%-%Min%-%Sec%"
:: remove echo here if you like
echo "dirName"="%dirName%"
this worked better for me,
#echo off
set temp=%DATE:/=%
set dirname="%temp:~4,4%%temp:~2,2%%temp:~0,2%"
mkdir %dirname%
For YYYY.MM.DD format with HUN settings use following. It converts "2021. 02. 23." to "2021.02.23":
SET dirname="%date:~0,5%%date:~6,3%%date:~10,2%"
md %dirname%
G:
cd G:/app/
mkdir %date:~7,2%%date:~-10,2%%date:~-4,4%
cd %date:~7,2%%date:~-10,2%%date:~-4,4%
sqlplus sys/sys as sysdba #c:/new
I needed both the date and time and used:
mkdir %date%-%time:~0,2%.%time:~3,2%.%time:~6,2%
Which created a folder that looked like:
2018-10-23-17.18.34
The time had to be concatenated because it contained : which is not allowed on Windows.
setlocal enableextensions
set name="%DATE:/=_%"
mkdir %name%
to create only one folder like "Tue 01_28_2020"

Resources