Batch: Timestamp to UNIX Time - batch-file

For all I know, Batch does not have a command that gives the UNIX time. The closest one I can find is %time%, which only displays the timestamp.
Is there a command, or set of commands in Batch with which you can get the UNIX time?

There's Richie Lawrence's batch library that has all those nifty handy scripts. The one you need is DateToSec (which uses GetDate and GetTime).
Here's a simplified script, that employs a little WMI:
#echo off
setlocal
call :GetUnixTime UNIX_TIME
echo %UNIX_TIME% seconds have elapsed since 1970-01-01 00:00:00
goto :EOF
:GetUnixTime
setlocal enableextensions
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do (
set %%x)
set /a z=(14-100%Month%%%100)/12, y=10000%Year%%%10000-z
set /a ut=y*365+y/4-y/100+y/400+(153*(100%Month%%%100+12*z-3)+2)/5+Day-719469
set /a ut=ut*86400+100%Hour%%%100*3600+100%Minute%%%100*60+100%Second%%%100
endlocal & set "%1=%ut%" & goto :EOF
The result will be returned into the first parameter passed to GetUnixTime, i.e. %UNIX_TIME%.
For example:
1341791426 seconds have elapsed since 1970-01-01 00:00:00
Hope it helps!

create a .bat file called "getUtime.bat"
#echo off
echo WScript.Echo(new Date().getTime()); > %temp%\time.js
cscript //nologo %temp%\time.js
del %temp%\time.js
and call like this
"C:\>getUTime"
1430894237616

What about simple 1-line long C program returning UNIX timestamp? You can retrieve value from %errorlevel% in batch script.
#include <stdio.h>
#include <time.h>
int main(void)
{
return (int) time(NULL);
}
In my test in command prompt it worked:
C:\Users\dabaran\Desktop\cs50\src\C>.\time || echo %errorlevel% && set mytstamp=%errorlevel%
1419609373
C:\Users\dabaran\Desktop\cs50\src\C>echo %mytstamp%
1419609373

There's a really simple way of doing this in a single batch file with no external scripts, files, libraries, etc.
<!-- :
for /f "tokens=* usebackq" %%a in (`start /b cscript //nologo "%~f0?.wsf"`) do (set timestamp=%%a)
echo %timestamp%
pause
exit /b
-->
<job><script language="JavaScript">
WScript.Echo(new Date().getTime());
</script></job>
The way it works is, code for a batch script AND code for a JS file are contained in the same .cmd or .bat file. you can force cscript to run the batch file as a script by commenting out the batch code and the : after the first line means batch will ignore it and run the batch code directly. so there you go!

There is no batch command for returning UNIX time. Your only options would be to write a program which could be run from a batch file that would return the UNIX time, or you could use the Windows PowerShell.

By far best solution is to download a freestanding date.exe unix-port.
Recommend that you rename it to unixdate.exe, to avoid conflict with MS Date command.
Get it from here
download & unzip. As far as I know, all the utilities are 'portable', that is, they don't require any installation program for them to work. I've only used a few (rm.exe & date.exe).
Also, you can ReName the exe's in case they might match other system utils you already have
Find the actual executable ports in the subfolder (usr\local\wbin)
To get HELP info type the command followed with --help (must spell help in lowercase)
Example:
((PROMPT)):unixdate +%Y%M%d
20141704
((PROMPT)):unixdate +%Y%b%d
2014Sep04

Related

Am I the only one who have this problem: While running something like .bat, the "X:\..\..path" often becomes ""X:\..\path and producing errors?

While running something like .bat, the "X:\..\..path" often becomes ""X:\..\path and producing errors. For example, I was installing apktool, then it just appeared this:
'""C:\Program' is not recognized as an internal or external command,
operable program or batch file.
I then copy the command and put one of the double quote to the end, which is like this: "C:\Program"
And everything just went smoothly, installation was successful. Then I tried to decode an apk, and the exactly same problem occurred: '""C:\Program' is not recognized as an internal or external command, operable program or batch file. This time I have no idea how to fix it, it's not like the .bat now, I cannot get the #echo on and copy the last command and edit it. So I am here to ask: If I am the only one who met this? Any way to fix this? Thank you.
My command:
apktool d test.apk
Image of running a decode command : 1
apktool.bat content:
#echo off
setlocal
set BASENAME=apktool_
chcp 65001 2>nul >nul
set java_exe=java.exe
if defined JAVA_HOME (
set java_exe="%JAVA_HOME%\bin\java.exe"
)
rem Find the highest version .jar available in the same directory as the script
setlocal EnableDelayedExpansion
pushd "%~dp0"
if exist apktool.jar (
set BASENAME=apktool
goto skipversioned
)
set max=0
for /f "tokens=1* delims=-_.0" %%A in ('dir /b /a-d %BASENAME%*.jar') do if %%~B gtr !max! set max=%%~nB
:skipversioned
popd
setlocal DisableDelayedExpansion
rem Find out if the commandline is a parameterless .jar or directory, for fast unpack/repack
if "%~1"=="" goto load
if not "%~2"=="" goto load
set ATTR=%~a1
if "%ATTR:~0,1%"=="d" (
rem Directory, rebuild
set fastCommand=b
)
if "%ATTR:~0,1%"=="-" if "%~x1"==".apk" (
rem APK file, unpack
set fastCommand=d
)
:load
"%java_exe%" -jar -Duser.language=en -Dfile.encoding=UTF8 "%~dp0%BASENAME%%max%.jar" %fastCommand% %*
rem Pause when ran non interactively
for /f "tokens=2" %%# in ("%cmdcmdline%") do if /i "%%#" equ "/c" pause
Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier. If the syntax set var="value" is used, then the quotes become part of the value assigned.
set java_exe="%JAVA_HOME%\bin\java.exe"
Should be
set "java_exe=%JAVA_HOME%\bin\java.exe"
(apply this principle throughout your code)
Then, if you require " anywhere, insert it where it's needed - don't try to include it as part of a variable's value.
This should clean up at least some of your problems.

How to delete all hardlinks of multiple files on windows 10?

I create a lot of hardlinks every week. When time comes to clean them, I find myself using the "DeleteAllHardlinks.bat" for ln (https://schinagl.priv.at/nt/ln/ln.html) but I have to drag and drop everyfile one after the other.
I would love to find a way to just select 100 files and drop them on the .bat, wait a while and find all those files and hardlinks deleted for good. Is there anyway to change the .bat file to allow this? (or maybe any other different method to acomplish the same?)
#echo off
REM
REM Check for commandline args
REM
if "[%~1]" == "[]" goto error
set LN=ln.exe
REM
REM List hardlink sibblings and delete all siblings
REM
for /f "delims=" %%a in ('#%LN% --list "%~1"') do (
del /f "%%a"
)
goto ausmausraus
:error
echo DeleteAllHardlinks: Argument is missing. Usage DeleteAllHardlinks ^<filename^>
echo e.g. DeleteAllHardlinks c:\data\myfile.txt
:ausmausraus
echo on
Thanks in advance!
Big thanks to Mofi!
The batch file could be very easily modified to support not just first argument, but all file name argument strings passed to the batch file by using one more for loop and %* as explained by call /?, i.e. use as replacement for the existing for loop:
for %%I in (%*) do for /F "delims=" %%J in ('ln.exe --list "%%~I" 2^>nul') do del /F "%%~J"
But the application starting the batch file has to pass each file name enclosed in double quotes to work properly.
Just using the for as offered in the comment solved the issue perfectly.

How to fetch file time which is last created using batch script

I have one folder which contain another subfolder and that subfolder contains different extensions file.
Now I want using batch script how to extract name and time of that file in a subfolder.
I tried but failed to retrieve time of that file which is located in subfolders.
I want only this code in the batch script only.
using substitution of variable reference for /?, echo can be changed by any other command or call
command-line
for %f in (filepath\pattern) do echo "%f : %~tf"
in a script the percent sign must be double
for %%f in (filepath\pattern) do echo "%%f : %%~tf"
EDIT after comment
here an example of how to use labels to simulate function and to avoid expansion tricks, note that labels are not exactly functions they are executed in normal flow, that's why there's goto :main to skip :process and goto :eof to return.
#echo off
goto :main
:process
echo file name is: %~1 and time is %~2
goto :eof
:main
for %%x in (AppData\Local\*.*) do call :process "%%x" "%%~tx"
but with batch script command set is very limited, also should be noted that date and time output can't be formatted and are dependent of system language settings.
If powershell can be used, it's worth taking the time to learn.
Different file time properties :
$file.CreationTime
$file.CreationTimeUtc
$file.LastAccessTime
$file.LastAccessTimeUtc
$file.LastWriteTime
$file.LastWriteTimeUtc

Suspend all processes from a specified folder

What I'm trying to do is suspend multiple processes from a single folder in Windows 7. I can get a list of such proccessses using the following commands:
WMIC PROCESS WHERE 'ExecutablePath like "c:\\users%"' GET
or
WMIC PROCESS WHERE 'ExecutablePath like "c:\\users%"' LIST
Then I need to suspend the proccesses that are returned by those commands. I can do that by using PsSuspend software. So, the only thing I have troubles with is looping through the list and executing this command for each process. It's rather easy to do in bash scripts, but how do I do it easily in Windows? I would prefer to use a .bat file or something similar, so it won't get overly complicated.
Here's an example:
#Echo Off
SetLocal EnableExtensions
Rem Command
(Set WC=Process)
Rem Filter
(Set WF=ExecutablePath Like)
Rem Value
(Set FV=%UserProfile%)
Rem Output
(Set RO=ProcessID)
Rem Run
(Set RC=PsSuspend)
For /F "UseBackQ Skip=1" %%A In (
`WMIC %WC% Where "%WF% '%FV:\=\\%%%'" Get %RO%`) Do For %%B In (%%A
) Do %RC% %%B
I changed line 9 to %UserProfile% you can change it back to C:\Users if you think I've assumed wrongly.

How to run several shortcuts (.lnk files) with a script in Windows?

I’m trying to create a script to run all the tools I use working in a particular project (dor instance, gulp, phpstorm, php server, etc.)
I’d like to run shortcuts but not executable files. I can see two possible ways to achieve it in Windows:
VbScript
cmd.exe
Unfortunately, I’ve failed both:
1) WshShell fire .lnk file and I can't find an alternative way to do that:
To do so I’m trying to write .cmd file or .vbs
However, I’ve got the problem in each way.
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "notepad.exe" ' Works alright
WshShell.Run "C:\Users\eugene\Desktop\gulp EngMe.lnk" ' got an Exception: Unknown Exception
2) .cmd script waits for closing previously started app:
#rem urls and filesystem shortcuts start alright:
"C:\Users\eugene\Desktop\8000.url"
"C:\Users\eugene\Desktop\project_folder.lnk"
#rem the following two commands are starting sequentially, when the previous one has closed.
"notepad.exe"
#rem shortcut to %windir%\system32\notepad.exe:
"C:\Users\eugene\Desktop\Notepad_.lnk"
What I'm doing wrong and is there another way to do what I'm trying?
Paths with spaces must be "quoted" when fed to .Run so:
WshShell.Run """C:\Users\eugene\Desktop\gulp EngMe.lnk"""
Will work fine.
Try using powershell for scripting.
Look at the question - Execute shortcuts like programs
Look at Mark Schill's answer using invoke-item to launch .lnk files like programs.
This is probably your best way to address your script challenges.
You can check the shortcutjs.bat which is capable to read a .lnk file properties. With this you will execute all .lnk files in the current directory in the correct working directory:
#echo off
for %%# in (*.lnk) do (
call :executeShortcut "%%#"
)
exit /b %errorlevel%
:executeShortcut - %1 - shortcut to execute
setlocal enableDelayedExpansion
for /f "tokens=1,* delims=:" %%a in ('call shortcutjs.bat -examine %1') do (
if /i "%%a" equ "Target" (
set "target=%%b"
set "target=!target:~1!"
)
if /i "%%a" equ "Working Directory" (
set "workdir=%%b"
set "workdir=!workdir:~1!"
)
)
start "%target%" /d "%workdir%" /wait /b "%target%"
exit /b %errorlevel%

Resources