add username and current date in destination folder robocopy [duplicate] - powershell

This question already has answers here:
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
(30 answers)
How to create a folder with name as current date in batch (.bat) files
(25 answers)
How to get the date format in windows batch file as 'yyyymmdd'?
(1 answer)
Batch command date and time in file name
(15 answers)
What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean?
(2 answers)
Closed 4 years ago.
I want to use a command to copy the entire contents of a folder (including subfolders) to a different drive.
For example:
robocopy c:\evernote\ e:\evernote\<datestamp>\
where <datestamp> is a new folder whose name represents the current date in this format:
2018_05_21
So, the target "evernote" folder will contain a series of subfolders, one folder for each date. Each subfolder will contain the files that were copied from source to target on that date.
For me, I don't think it matters if the command is copy, robocopy, xcopy, or whatever. However, I believe that robocopy is most up-to-date, and therefore most likely to be of future use to me.
BTW: To keep this simple, there's no need to allow for different time zones, and no need for "automation" - I will run the BAT file myself, and add automation later.
Thanks.

Because you're using, and happy to use, RoboCopy for the copying process, here's a method which also uses it to determine the date:
#Echo Off
Set "sd=C:\EverNote"
Set "dd=E:\EverNote"
Set "ds="
If Not Exist "%sd%\" Exit /B
For /F "Tokens=1-3Delims=/ " %%A In ('RoboCopy/NJH /L "\|" Null'
) Do If Not Defined ds Set "ds=%%A_%%B_%%C"
If Not Defined ds Exit /B
RoboCopy "%sd%" "%dd%\%ds%" /E
You can edit the locations in lines 2 and 3, (but do not remove the existing doublequotes or introduce your own, and do not include trailing backslashes with those folder names)

When writing in Batch, you should be able access the environment variable %date%.
This is a string of the current date.
You can try to use echo %date% to see what it looks like, and then split and recombine the string, so it fits your need.
Beware though, that the format of the string is dependent on how you set your datetime settings on your computer. If you change to use another format on the computer, the format of %date% will also change.

To generate a date in a certain format without worring about localization settings you can use this:
#echo off
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do #for /f %%# in ("%%#") do #set %%#
:echo %day%
:echo %DayOfWeek%
:echo %hour%
:echo %minute%
:echo %month%
:echo %quarter%
:echo %second%
:echo %weekinmonth%
:echo %year%
if %day% lss 10 set day=0%day%
if %month% lss 10 set month=0%month%
set f_date=%year%-%month%-%day%
echo %f_date%
The %date% variable format depends on the settings in the control panel and it's value will be different on different machines. For more ways to get a formatted date you can check this

This script uses PowerShell to get the datestamp in the desired format:
#Echo off
for /f "usebackqdelims=" %%D in (
`powershell -Nop -C "(Get-Date).ToString('yyyy_MM_dd')"`
) Do Set "datestamp=%%D"
Echo robocopy c:\evernote\ e:\evernote\%datestamp%\
Sample output:
robocopy c:\evernote\ e:\evernote\2018_06_02\

Related

Batch Script that gives unique time stamp to rename bulk files

I used this script to rename files in bulk with a unique time stamp in a batch file. The idea is to use the second and millisecond to create a unique number, which is added to the filename. The why? The filenames being used is so similar in the naming convention that it is triggering errors on the import program into the database. What doesn't trigger the error is the uniqueness of the filename, which is why I thought of a second and millisecond stamp to the prefix. Now, the code works as intended, but the stamp is not unique. It is as if the code pulls the value from the system and applies to all of the files in the folder instead of one file at a time.
Assume my file names are like this:
File1.txt
File2.txt
File3.txt
File4.txt
When the script is run, it renames the files like this:
1410File1.txt
1410File2.txt
1410File3.txt
1410File4.txt
I was hoping the script would do it like this:
1410File1.txt
1411File2.txt
1412File3.txt
1413File4.txt
The code I used to help me with this problem:
#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 Mil=%dt:~14,6%
set stamp=%Sec%%Mil%
CHDIR /D "c:\TEST\FILES\"
for %%a in (*.*) do ren "%%a" "%stamp%%%a"
Is there an additional programming code that is needed to ensure each filename is renamed differently? I'm on Windows 10 using a simple .bat file. On any given day, I would end up renaming anywhere from 600 up to 1000 files in one sitting so any help would be greatly appreciated!
Thanks in advance!
You answered your own question:
Now, the code works as intended, but the stamp is not unique. It is as if the code pulls the value from the system and applies to all of the files in the folder instead of one file at a time.
Take a look at your code. You
Compute the timestamp once at the start of the run:
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 Mil=%dt:~14,6%
set stamp=%Sec%%Mil%
cd down to the desired directory:
CHDIR /D "c:\TEST\FILES\"
iterate over the files in the directory, adding the same timestamp to each file:
for %%a in (*.*) do ren "%%a" "%stamp%%%a"
You need to recompute the timestamp on every iteration of the final loop.
I would also add a pause of a few milliseconds in the loop to ensure that at least 1 millisecond has elapsed between computations of the timestamp.

How to create a batch that creates a directory named the current date and time, and then copy files in it?

I have to seperate codes.
This creates a directory with only the date, but i don't know how to put the time on the end.
for /f "tokens=1* delims=" %%a in ('date /T') do set datestr=%%a
mkdir c:\%date:/=%
And I have this to copy the files:
robocopy "%appdata%\saves" "C:\Users\redfi\OneDrive\Savesbackup" /e /xf
They both work individually, but I want to put them in one batch.
I want it to create the directory with the current date and time, and then copy the saves in it. So I can restore older saves if I want.
Thank you!
I managed to figure it out. You might need to edit the date formats.
echo off
set CUR_YYYY=%date:~0,4%
set CUR_MM=%date:~5,2%
set CUR_DD=%date:~8,2%
set CUR_HH=%time:~0,2%
if %CUR_HH% lss 10 (set CUR_HH=0%time:~1,1%)
set CUR_NN=%time:~3,2%
set CUR_SS=%time:~6,2%
set CUR_MS=%time:~9,2%
set SUBFILENAME=%CUR_YYYY%.%CUR_MM%.%CUR_DD%_%CUR_HH%.%CUR_NN%
mkdir C:\Users\redfi\OneDrive\Minecraftbackup\%SUBFILENAME%
robocopy "%appdata%\.minecraft\saves" "C:\Users\redfi\OneDrive\Minecraftbackup\%SUBFILENAME%" /e /xf

Use Variable insted of Get-Date in powershell

I am using PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')" in batch script.
I want to use a variable instead of Get-Date function. Is it possible?
ADate is the variable name!
Edited:
As suggested, my script is:
For /F UseBackQ %%A In (
`PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "Freq=%%A"
Adate is simple string which comes from the file name, and has a value like 16112016.
You need to use a for loop to get the output of an external command in a batch variable:
#echo off
for /f "usebackq tokens=*" %%d in (`powershell "..."`) do set "adate=%%d"
echo %adate%
The usebackq and backticks are just so you don't need to escape the nested single quotes in your command string.
Ok. I got my crystal ball and asked it: "What is the solution here?", and it replied: "Change
PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"
by
PowerShell "(Get-Date -Date '!Adate:~4!-!Adate:~2,2!-!Adate:~0,2!').AddDays(-7).ToString('ddMMyyyy')"
", but I have no idea what it is talking about! ;)
You can store the output of the powerShell command into a file and then read that file after that delete that temporary file.
PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')" >temp.txt
set /p myVarDate= < date_Shell.txt
echo Date from Shell %myVarDate%
del temp.txt
The following takes the last modified time from a known file's properties and creates a variable with a date seven days earlier, (obviously changing C:\Test\TestFile.ext as necessary):
For /F UseBackQ %%A In (
`PowerShell "((gi 'C:\Test\TestFile.ext').LastWriteTime).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "ADate=%%A"
Edit
The following example takes a date string with a known format, (in this case provided in two variables). It then converts that string to a date object, subtracts seven days and sets it back to a string in the new %ADate% variable:
#Echo Off
Set "DateStr=16112016"
Set "DFormat=ddMMyyyy"
For /F UseBackQ %%A In (`Powershell^
"([datetime]::ParseExact('%DateStr%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-7).ToString('%DFormat%')"
`) Do Set "ADate=%%A"
Echo(%ADate%
Timeout -1

Store the formatted date value to an environment variable for command line

I am trying to store the formatted date value to an environment variable. Below is my batch script.
set now="`powershell get-date -format \"{yyyy-mm-dd}\"`"
dsjob -run -jobstatus -param current_timestamp=%now% dstage1 TheAge
This is not working. I am a Unix guy and I expect an easier way of doing this than using for loops and other solutions provided.
How to store the executed command value to an environment variable?
Excuse me. May I offer you a different point of view?
There are several different ways to get the current date in YYYY-MM-DD format, but powershell is not precisely the best one. The powershell.exe program is a file about 465 MB size that is best suited to be loaded once in order to execute a large .ps1 script. Using this program (that includes all the advanced facilities of the powershell programming language) just to get the current date is certainly a waste of resources that may take several seconds in slow machines.
Another commonly used approach in Batch files is wmic, a standard Windows command that provides a series of data about the computer and its elements, but it is also a file 495 MB size that perform extensive operations and is not precisely fast.
The third option is to use a VBScript or JScript script; these are programming languages preinstalled on all Windows versions from XP on. In this case the run-time support for these languages is a compiler of the same family of C, C++ and JavaScript, so it is very efficient. The VBScript/JScript compiler file (cscript.exe) is just 143 MB size and is certainly the most efficient way to get the current date in YYYY-MM-DD format independent from locale settings, that is, it may be used in a wide range of different computers.
The last phrase also suggest the last method. If the Batch file will always run in the same computer, then you don't need the advanced features of previous methods; you may get the date directly from the %date% internal variable. This method is the most efficient one, because it only uses internal Batch commands.
Below there is a Batch file that show how to use all four previous methods. If you execute this Batch file several times, you will realize that the powershell method is precisely the less efficient one.
#echo off
setlocal
rem Get current date in YYYY-MM-DD format, locale independent
rem Powershell method
for /F %%a in ('powershell get-date -format "{yyyy-mm-dd}"') do set "now=%%a"
echo Powershell: %now%
echo/
rem WMIC method
for /F "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "now=%dt:~0,4%-%dt:~4,2%-%dt:~6,2%"
echo WMIC: %now%
echo/
rem JScript method
echo var d=new Date();WScript.Echo(d.getFullYear()+"-"+(101+d.getMonth()).toString().substr(1)+"-"+(100+d.getDate()).toString().substr(1));>now.js
for /F "delims=" %%a in ('now.js') do set "now=%%a"
echo JScript: %now%
echo/
rem Get current date in YYYY-MM-DD format via %date% variable, locale dependent
for /F "tokens=1-3 delims=/" %%a in ("%date%") do set "now=%%c-%%a-%%b"
echo Pure Batch: %now%
echo/
You would be better off using a PowerShell script to do the whole thing; it will be simpler and PowerShell's operators and syntax are more bash-like (certainly not a drop in replacement, but still).
From within PowerShell, this could be a single line:
dsjob -run -jobstatus -param current_timestamp=$(Get-Date -Format yyyy-MM-dd) dstage1 TheAge
Of course you could use a variable also:
$now = Get-Date -Format yyyy-MM-dd
dsjob -run -jobstatus -param current_timestamp=$now dstage1 TheAge
Is there a reason you must use a batch file?

how to find the last time stamp of the particular TYPE file in that directory?

how get the date and time of the last modified particular TYPE file in that directory
let me explain with an example
if i use the command dir *.reo /o:d
i get the all *.reo files in that directory sorted according to the date ..
this is the the last line of the output
29-03-2010 11.31 arun.reo
now i just want to copy the date and time of the last created file in variable or file .is it possible ?
You can do this using a batch file like this:
#echo off
setlocal enableextensions
for /f "delims=" %%f in ('dir *.reo /o:-d /b') do (
set dt=%%~tf
goto endloop
)
: endloop
echo %dt%
A little explanation:
dir *.reo /o:-d /b produces a list of all .reo files in the current directory, sorted by date in descending order (so that the last modified file comes first).
%%~tf expands to the date of the file specified by the %f variable.
It depends on what os your using. If you want just the last file
command one pipes the complete directory into a temp file
dir *.reo /o:d > temp.txt;
command two gets the last line of the temp file. Only works if you have the windowserver 2003 install which the link is provided below.
tail - 1 temp.txt;
Go to the Microsoft Windows Server 2003 download section at http://www.microsoft.com/windowsserver2003/
downloads/tools/default.mspx. Or, if that link does not work, visit http://www.microsoft.com/ and search for "Windows 2003". Once there, choose the "Downloads -> Tools" link.