Calling Date Modified in CMD - command-line

Basically just attempting to create a very basic program that will display the last modified date of a file on our server. Problem is I have no idea how to write it. This is what I attempted
cd \\Server\Folder
msg dir
I also ran into the problem "CMD Does not support UNC Paths as Current Directories" when I tried to change the CD to our servers directory.
What I would like it to do is display in a dialog box the modified date of a "Text.txt" located on our server \\Server\Folder
Any and all help is appreciated

Next .bat script should work:
set "_folder=\\Server\Folder"
set "_filename=Text.txt"
set "_filedatetime=N/A"
pushd %_folder%
for %%G in (%_filename%) do (
rem echo %%~tG %%~fG
if not "%%~tG"=="" set "_filedatetime=%%~tG"
)
popd
echo file %_folder%\%_filename% date and time: %_filedatetime%
Note there is no dialog box in pure cmd command line interpreter, try set /P.
Resources:
SET: Display, set, or remove CMD environment variables
PUSHD, POPD: and UNC Network paths
FOR commands
~ Parameter Extensions

Related

PowerShell: Open file via .bat script

imagine I have a files with certain extensions (for example '.abc').
The default program I set for files with this special extension is a batch script with powershell commands in it, so when I doubleclick the file, it runs the script. It works.
Now my question is, can I somehow get the file path of the .'abc' file I opened? Is there a command for this?
Thank you.
Inside of your batch file it should be possible to access the ".abc" file via parameter %1.
Per default Windows sends the filename of the file you doubleclick to the receiving program (or batch script) as parameter one.
Try this inside of your batch file (near the top) and pick what suits your needs:
echo param1: %1
echo param1 unquoted: %~1
echo drive: %~d1
echo drive and path: %~dp1
echo filename and extension only: %~nx1
set myparam=%~1
echo myParam: %myparam%
See the help documentation of for for the "%~..." syntax by executing for /? in a cmd.exe command window. (Or read here: What does %~dp0 mean, and how does it work?)

Is there a tag I could add to a ".bat" file to stop command window being displayed [duplicate]

How can I run a CMD or .bat file in silent mode? I'm looking to prevent the CMD interface from being shown to the user.
Include the phrase:
#echo off
right at the top of your bat script.
I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)
That should answer your question.
Here it is:
From your first script, call your second script with the following line:
wscript.exe invis.vbs run.bat %*
Actually, you are calling a vbs script with:
the [path]\name of your script
all the other arguments needed by your script (%*)
Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:
intWindowStyle : 0 means "invisible windows"
bWaitOnReturn : false means your first script does not need to wait for your second script to finish
See the question for the full invis.vbs script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
^
means "invisible window" ---|
Update after Tammen's feedback:
If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:
You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.
I think this is the easiest and shortest solution to running a batch file without opening the DOS window, it can be very distracting when you want to schedule a set of commands to run periodically, so the DOS window keeps popping up, here is your solution.
Use a VBS Script to call the batch file ...
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run chr(34) & "C:\Batch Files\ mycommands.bat" & Chr(34), 0
Set WshShell = Nothing
Copy the lines above to an editor and save the file with .VBS extension. Edit the .BAT file name and path accordingly.
Use Advanced BAT to EXE Converter from http://www.battoexeconverter.com
This will allow you to embed any additional binaries with your batch file in to one stand alone completely silent EXE and its freeware
Use Bat To Exe Converter to do this
http://download.cnet.com/Bat-To-Exe-Converter/3000-2069_4-10555897.html (Choose Direct Download Link)
1 - Open Bat to Exe Converter, select your Bat file.
2 - In Option menu select "Invisible Application", then press compile button.
Done!
Try SilentCMD. This is a small freeware program that executes a batch file without displaying the command prompt window.
If i want to run command promt in silent mode, then there is a simple vbs command:
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"
if i wanted to open an url in cmd silently, then here is a code:
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe http://otaxi.ge/log/index.php", 0)
'wait 10 seconds
WScript.sleep 10000
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"
I'm pretty confident I like this method the best. Copy and paste the code below into a .vbs file. From there you'll call the batch file... so make sure you edit the last line to specify the path and name of the batch file (which should contain the file you'd like to launch or perform the actions you need performed)
Const HIDDEN_WINDOW = 12
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("C:\PathOfFile\name.bat", null, objConfig, intProcessID)
It definitely worked for me. Comments are welcomed :)
Another way of doing it, without 3rd party programs nor converters ("batch to exe" programs actually just put your batch file in the tmp folder and then run it silently so anyone can just fetch it from there an get your code) no vbs files (because nobody knows vbs) just one line at the beginning of the batch file.
#echo off > NUL
The below silent .bat file code prevents the need to have two bat files (using "goto" and ":").
It does it all in the same .bat file. Tested and confirmed working in Windows 10
Make sure you replace "C:\pathToFile\ThisBatFile.bat " with the path to this same .bat file! Keep the space after ".bat".
#echo off
if [%1]==[] (
goto PreSilentCall
) else (
goto SilentCall
)
:PreSilentCall
REM Insert code here you want to have happen BEFORE this same .bat file is called silently
REM such as setting paths like the below two lines
set WorkingDirWithSlash=%~dp0
set WorkingDirectory=%WorkingDirWithSlash:~0,-1%
REM below code will run this same file silently, but will go to the SilentCall section
cd C:\Windows\System32
if exist C:\Windows\Temp\invis.vbs ( del C:\Windows\Temp\invis.vbs /f /q )
echo CreateObject("Wscript.Shell").Run "C:\pathToFile\ThisBatFile.bat " ^& WScript.Arguments(0), 0, False > C:\Windows\Temp\invis.vbs
wscript.exe C:\Windows\Temp\invis.vbs Initialized
if %ERRORLEVEL%==0 (
echo Successfully started SilentCall code. This command prompt can now be exited.
goto Exit
)
:SilentCall
cd %WorkingDirectory%
REM Insert code you want to be done silently.
REM Make sure this section has no errors as you won't be able to tell if there are any,
REM since it will be running silently. You can add a greater than symbol at the end of
REM your commands in this section to output the results to a .txt file for the purpose
REM of debugging this section of code.
:Exit
If your .bat file needs more than just the "Initialized" argument (which tells the bat file to go to :SilentCall section), add "^& WScript.Arguments(1)," , "^& WScript.Arguments(2)," ,etc. depending on the number of arguments, then edit the line where wscript.exe is called:
"wscript.exe C:\Windows\Temp\invis.vbs Initialized BatFileArgOne BatFileArgTwo"
I'm created RunApp to do such a job and also using it in my production env, hope it's helps.
The config like below:
file: config.arg
:style:hidden
MyBatchFile.bat
arg1
arg2
And launch runapp.exe instead.

How can I return to the previous directory in windows command prompt?

I often want to return to the previous directory I was just in in cmd.exe, but windows does not have the "cd -" functionality of Unix. Also typing cd ../../.. is a lot of typing.
Is there a faster way to go up several directory levels?
And ideally return back afterwards?
This worked for me in powershell
cd ..
Steps:
pushd . (Keep old folder path on the stack)
cd ..\.. (Move to the folder whare you like to)
popd (Pop it from the stack. Meaning, Come back to the old folder)
On Windows CMD, I got used to using pushd and popd. Before changing directory I use pushd . to put the current directory on the stack, and then I use cd to move elsewhere. You can run pushd as often as you like, each time the specified directory goes on the stack. You can then CD to whatever directory, or directories , that you want. It does not matter how many times you run CD. When ready to return , I use popd to return to whatever directory is on top of the stack. This is suitable for simple use cases and is handy, as long as you remember to push a directory on the stack before using CD.
Run cmd.exe using the /k switch and a starting batch file that invokes doskey to use an enhanced versions of the cd command.
Here is a simple batch file to change directories to the first parameter (%1) passed in, and to remember the initial directory by calling pushd %1.
md_autoruns.cmd:
#echo off
cd %1
pushd %1
title aliases active
cls
%SystemRoot%\System32\doskey.exe /macrofile=c:\tools\aliases
We will also need a small helper batch file to remember the directory changes and to ignore changes to the same directory:
mycd.bat:
#echo off
if '%*'=='' cd & exit /b
if '%*'=='-' (
cd /d %OLDPWD%
set OLDPWD="%cd%"
) else (
cd /d %*
if not errorlevel 1 set OLDPWD="%cd%"
)
And a small aliases file showing what to do to make it all work:
aliases:
cd=C:\tools\mycd.bat $*
cd\=c:\tools\mycd.bat ..
A:=c:\tools\mycd.bat A:
B:=c:\tools\mycd.bat B:
C:=c:\tools\mycd.bat C:
...
Z:=c:\tools\mycd.bat Z:
.=cd
..=c:\tools\mycd.bat ..
...=c:\tools\mycd.bat ..\..
....=c:\tools\mycd.bat ..\..\..
.....=c:\tools\mycd.bat ..\..\..\..
......=c:\tools\mycd.bat ..\..\..\..\..
.......=c:\tools\mycd.bat ..\..\..\..\..\..
........=c:\tools\mycd.bat ..\..\..\..\..\..\..
.........=c:\tools\mycd.bat ..\..\..\..\..\..\..\..
tools=c:\tools\mycd.bat C:\tools
wk=c:\tools\mycd.bat %WORKSPACE%
Now you can go up a directory level by typing ..
Add another . for each level you want to go up.
When you want to go back, type cd - and you will be back where you started.
Aliases to jump to directories like wk or tools (shown above) swiftly take you from location to location, are easy to create, and can really help if you work in the command line frequently.
You could use the command:
cd ..\ -> To go up one level
cd ..\..\ -> To go up two levels
Note the space after cd

Batch Code to Skip Script if File is too Old

My Problem
As there are a ton of threads that address 'using a batch file to return file modify date' (or delete files older than, etc) - let me first specify my issue.
I'm looking to create a batch (not PowerShell, etc) that will return the last modify date of a specific file given UNC path and filename.
Code, Attempt 1
I've taken a peek at a few potential solutions on other threads, but I've run into a number of unique issues. The first and most obvious solution for this would be the "ForFiles" command in batch. For example:
set myPath=\\myUNCpath
set myFile=myFileName.csv
forfiles /p "%myPath%" /m %myFile% /c "GoTo OldFile" /d -6
Thus, if the file is older than I want -- jump to a specific section of my batch for that. However, this yields the error:
ERROR: UNC paths (\machine\share) are not supported.
However, this cmd won't work due to the use of UNC (which is critical as this batch is called by system's task scheduler). So it seems like the 'ForFiles' cmd is out.
Code, Attempt 2
I could go a more round about way of doing it, but simply retrieving the last modified date of the file (which in batch would return a string). I can truncate the string to the necessary date values, convert to a date, and then compare to current date. To do that, I've also looked into just using a for loop such as:
set myFile=\\myUNCpath\myFileName.csv
echo %myFile%
pause
FOR %%f IN (%myFile%) DO SET myFileDate=%%~tf
echo %myFileDate%
pause
Though my first debug echo provides the proper full file name, my second debug just returns ECHO is off., which tells me it's either not finding the file or the for loop isn't returning the file date. Not sure why.
I've also tried minor changes to this just to double check environmental variable syntax:
FOR %%f IN (%myFile%) DO SET myFileDate=%%~ta
Returns %ta
And finally:
FOR %%f IN (%myFile%) DO SET myFileDate=%~ta
Which without the extra '%', just crashes the batch.
I'm really at a loss at this point. So any tips or guidance would be greatly appreciated!
Using forfiles to a UNC path can be used using PushD
For just echoing the file older than x in UNC path, simply just use
PushD %myPath% &&(
forfiles -s -m %myFile% -d -6 -c "cmd /c echo /q #file
) & PopD
Here is one way how to use goto if file older than x found in UNC path using your examples.
if not exist "C:\temp" mkdir C:\temp
if not exist "C:\temp\test.txt" echo.>"c:\temp\test.txt"
break>"c:\temp\test.txt"
set myPath=\\myUNCpath
set myFile=myFileName.csv
PushD %myPath% &&(
forfiles -s -m %myFile% -d -6 -c "cmd /c echo /q #file >> c:\temp\test.txt"
) & PopD
for /f %%i in ("C:\temp\test.txt") do set size=%%~zi
if %size% gtr 0 goto next
:next
Huge thanks to both #Squashman and #MadsTheMan for the help. Luckily this batch finally is the piece of code that I can take to my boss to push switching over to at least using PowerShell!
Anyway, for those of you looking for the best way to get a UNC path file's modify date, here is what I've come up with. Not very different than other threads (and a thanks goes out to Squashman for spotting my missing " " in the for loop).
set myFile=\\myUNCpath\myFileName.ext
FOR %%f IN ("%myFile%") DO SET myFileDate=%%~tf
::And if you'd like to try to do long winded calculations you can further break the dates down via...
set fileMonth=%myFileDate:~0,2%
set fileDay=%myFileDate:~3,2%
set fileYear=%myFileDate:~6,4%
set currentDate=%date%
set currentMonth=%currentDate:~4,2%
set currentDay=%currentDate:~7,2%
set currentYear=%currentDate:~10,4%
The plan was to then convert the strings to integers, and then use a switch-case block to determine if the variance between dates was acceptable... blah blah blah.
Long story short - if you are limited to batch (and not creating secondary files -- such as a csv or the temp file suggested by MadsTheMan) you're going to have a really long script on your hands that still might have flaws (like leap year, etc unless you're adding even MORE code), when you could just make the comparison calculation using one line of code in other programs.

Tool for commandline "bookmarks" on windows?

Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like:
C:\> go home
D:\profiles\user\home\> go svn-project1
D:\projects\project1\svn\branch\src\>
I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows.
Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.
What you are looking for is called DOSKEY
You can use the doskey command to create macros in the command interpreter. For example:
doskey mcd=mkdir "$*"$Tpushd "$*"
creates a new command "mcd" that creates a new directory and then changes to that directory (I prefer "pushd" to "cd" in this case because it lets me use "popd" later to go back to where I was before)
The $* will be replaced with the remainder of the command line after the macro, and the $T is used to delimit the two different commands that I want to evaluate. If I typed:
mcd foo/bar
at the command line, it would be equivalent to:
mkdir "foo/bar"&pushd "foo/bar"
The next step is to create a file that contains a set of macros which you can then import by using the /macrofile switch. I have a file (c:\tools\doskey.macros) which defines the commands that I regularly use. Each macro should be specified on a line with the same syntax as above.
But you don't want to have to manually import your macros every time you launch a new command interpreter, to make it happen automatically, just open up the registry key
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun and set the value to be doskey /macrofile "c:\tools\doskey.macro". Doing this will make sure that your macros are automatically predefined every time you start a new interpreter.
Extra thoughts:
- If you want to do other things in AutoRun (like set environment parameters), you can delimit the commands with the ampersand. Mine looks like: set root=c:\SomeDir&doskey /macrofile "c:\tools\doskey.macros"
- If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM.
- You can also use doskey to control things like the size of the command history.
- I like to end all of my navigation macros with \$* so that I can chain things together
- Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them.
I was looking for this exact functionality, for simple cases. Couldn't find a solution, so I made one myself:
#ECHO OFF
REM Source found on https://github.com/DieterDePaepe/windows-scripts
REM Please share any improvements made!
REM Folder where all links will end up
set WARP_REPO=%USERPROFILE%\.warp
IF [%1]==[/?] GOTO :help
IF [%1]==[--help] GOTO :help
IF [%1]==[/create] GOTO :create
IF [%1]==[/remove] GOTO :remove
IF [%1]==[/list] GOTO :list
set /p WARP_DIR=<%WARP_REPO%\%1
cd %WARP_DIR%
GOTO :end
:create
IF [%2]==[] (
ECHO Missing name for bookmark
GOTO :EOF
)
if not exist %WARP_REPO%\NUL mkdir %WARP_REPO%
ECHO %cd% > %WARP_REPO%\%2
ECHO Created bookmark "%2"
GOTO :end
:list
dir %WARP_REPO% /B
GOTO :end
:remove
IF [%2]==[] (
ECHO Missing name for bookmark
GOTO :EOF
)
if not exist %WARP_REPO%\%2 (
ECHO Bookmark does not exist: %2
GOTO :EOF
)
del %WARP_REPO%\%2
GOTO :end
:help
ECHO Create or navigate to folder bookmarks.
ECHO.
ECHO warp /? Display this help
ECHO warp [bookmark] Navigate to existing bookmark
ECHO warp /remove [bookmark] Remove an existing bookmark
ECHO warp /create [bookmark] Navigate to existing bookmark
ECHO warp /list List existing bookmarks
ECHO.
:end
You can list, create and delete bookmarks. The bookmarks are stored in text files in a folder in your user directory.
Usage (copied from current version):
A folder bookmarker for use in the terminal.
c:\Temp>warp /create temp # Create a new bookmark
Created bookmark "temp"
c:\Temp>cd c:\Users\Public # Go somewhere else
c:\Users\Public>warp temp # Go to the stored bookmark
c:\Temp>
Every warp uses a pushd command, so you can trace back your steps using popd.
c:\Users\Public>warp temp
c:\Temp>popd
c:\Users\Public>
Open a folder of a bookmark in explorer using warp /window <bookmark>.
List all available options using warp /?.
With just a Batch file, try this... (save as filename "go.bat")
#echo off
set BookMarkFolder=c:\data\cline\bookmarks\
if exist %BookMarkFolder%%1.lnk start %BookMarkFolder%%1.lnk
if exist %BookMarkFolder%%1.bat start %BookMarkFolder%%1.bat
if exist %BookMarkFolder%%1.vbs start %BookMarkFolder%%1.vbs
if exist %BookMarkFolder%%1.URL start %BookMarkFolder%%1.URL
Any shortcuts, batch files, VBS Scripts or Internet shortcuts you put in your bookmark folder (in this case "c:\data\cline\bookmarks\" can then be opened / accessed by typing "go bookmarkname"
e.g. I have a bookmark called "stack.url". Typing go stack takes me straight to this page.
You may also want to investigate Launchy
With PowerShell you could add the folders as variables in your profile.ps1 file, like:
$vids="C:\Users\mabster\Videos"
Then, like Unix, you can just refer to the variables in your commands:
cd $vids
Having a list of variable assignments in the one ps1 file is probably easier than maintaining separate batch files.
Another alternative approach you may want to consider could be to have a folder that contains symlinks to each of your projects or frequently-used directories. So you can do something like
cd \go\svn-project-1
cd \go\my-douments
Symlinks can be made on a NTFS disk using the Junction tool
Without Powershell you can do it like this:
C:\>set DOOMED=c:\windows
C:\>cd %DOOMED%
C:\WINDOWS>
Crono wrote:
Are Environment variables defined via "set" not meant for the current session only? Can I persist them?
They are set for the current process, and by default inherited by any process that it creates. They are not persisted to the registry. Their scope can be limited in cmd scripts with "setlocal" (and "endlocal").
Environment variables?
set home=D:\profiles\user\home
set svn-project1=D:\projects\project1\svn\branch\src
cd %home%
On Unix I use this along with popd/pushd/cd - all the time.