windows batchfile: change filestamp - batch-file

I have several files where the filename consists of a date. I want to change the date & time of the files (filestamp) into that one which is in the filename by using a windows batchfile. Let assume the file is 2013-02-20.txt and I want that file having a datestamp correspondending to which is in the filename and thus set to 20130220, while the timestamp can be set to "00:00". I extract the year, month and date from the filename into variables but how to filestamp these files with that date & time?
for %%f in (*.txt) do (
set FILENAME=%%~nf
set YEAR=!FILENAME:~0,4!
set MONTH=!FILENAME:~5,2!
set DAY=!FILENAME:~8,2!
set TIME=00:00
)
Question is how to change the filedate and filetime using the variables YEAR, MONTH, DAY and TIME (in Linux I do it with the 'touch' command)?

I did my own CLI app written in .NET to get/set filestamps, it's so easy to use and has beneffits than filetouch for windows, maybe you will preffer to use mine app.
Download: http://elektrostudios.tk/FileDate.zip

Does it have to be a Batch File?
You can do it in Batch, but not easily. Stay with me here and don't lose heart. :)
Starting in this post - http://www.dostips.com/forum/viewtopic.php?f=3&t=4846
And there is some bleed-over to this post - http://www.dostips.com/forum/viewtopic.php?p=27422#p27422 and I will be perfectly honest with you, I have not re-timestamped a file using direct batch.
Have done it with the next thought or idea:
You can do this pretty easily in VBScript or in PowerShell..
VBS:
Set fso = CreateObject("Scripting.FileSystemObject")
' -- Re-date files
' Call Touch(Server.MapPath("/"), "somefile.htm", "2005-09-01")
' Call Touch("C:\", "somefile.txt", "2012-01-01")
Sub Touch(strDir, strFileName, NewDate)
Dim objShell, objFolder, objFile
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(strDir)
Set objFile = objFolder.ParseName(strFileName)
If fso.FileExists(strDir & strFileName) Then
objFile.ModifyDate = NewDate
End If
End Sub
PowerShell:
if ($DTNew) {
(dir $aZip).lastwritetime = $DTNew
}

I fixed it with 'touch' which is in the coreutils package. I downloaded coreutils from here. Then I added the folder C:\Program Files (x86)\GnuWin32\bin to the windows PATH and used this batch file:
#echo off
set TIME=0000
for %%f in (*.txt) do (
set FILENAME=%%~nf
set YEAR=!FILENAME:~0,4!
set MONTH=!FILENAME:~5,2!
set DAY=!FILENAME:~8,2!
set NEW_STAMP=!YEAR!!MONTH!!DAY!!TIME!
touch -t !NEW_STAMP! %%f
)
goto:EOF
:EOF
pause

Related

Batchjob for changing the date format in a filename

hope somebody can help me.
I need a .bat doing the following:
Run in folder "A" all the time
waiting for a file to appear in the following format:
1_33530_Jim_Hutchinson_m_23.04.1965_20210628-163636_D-Endo14.pdf
reformatting the file to
1_33530_Jim_Hutchinson_m_19650423_20210628-163636_D-Endo14.pdf
write the new file to folder B
Meaning in the filename the date format should change from DD.MM.YYYY to YYYYMMDD everything else
before and after should be untouched
How can I do that with a looping batch job?
Kind regards and thanks in advance
Sven
Split filename 1_33530_Jim_Hutchinson_m_23.04.1965_20210628-163636_D-Endo14.pdf to three part. Delimiter is point.
Using string substitute split 1_33530_Jim_Hutchinson_m_23 to 1_33530_Jim_Hutchinson_m_ and 23
set filename1=!temp_var1:~0,-2!
set day=!temp_var1:~-2!
Using string substitute split 1965_20210628-163636_D-Endo14 to 1965 and _20210628-163636_D-Endo14
set year=!temp_var2:~0,4!
set filename2=!temp_var2:~4!
Make new filename
set new_filename=!filename1!!year!!month!!day!!filename2!.pdf
full code
setlocal ENABLEDELAYEDEXPANSION
for %%f in (*.pdf) do (
for /f "delims=. tokens=1,2,3" %%a in ("%%f") do (
set temp_var1=%%a
set month=%%b
set temp_var2=%%c
set filename1=!temp_var1:~0,-2!
set day=!temp_var1:~-2!
set year=!temp_var2:~0,4!
set filename2=!temp_var2:~4!
set new_filename=!filename1!!year!!month!!day!!filename2!.pdf
copy %%f B\!new_filename!
)
)

How to pass a variable in a batch script during execution

I have a text file that has the record of all the services in a server. I want to keep '#' for the few entries at the beginning of the line. I have created one vbscript file that contains the following code:
Const Readpurpose = 1
Const Writepurpose = 2
strServiceMonFile = WScript.Arguments(0)
strOldText = WScript.Arguments(1)
strNewText = WScript.Arguments(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strServiceMonFile, Readpurpose)
strText = objFile.ReadAll
objFile.Close
Set objFile = objFSO.OpenTextFile(strServiceMonFile, Writepurpose)
strNewText = Replace(strText, strOldText, strNewText)
objFile.Write strNewText
objFile.Close
In order to execute the code, I am using a batch file and the code used is as follows:
cscript D:\Users\krkarthi\Desktop\replace.vbs "D:\Users\krkarthi\Desktop\test.txt" "Windows Update" "#Windows Update"
In the above mentioned batch code, I need to manually enter each and every entry which I need to keep # comment and for a plenty of services it is very difficult to proceed. I am thinking another way to have a separate text file lets say test1.txt that contains all the unwanted entries. A variable will define in a for loop to run on test1.txt and will run the above mentioned cscript code after do. The imaginative code is as follows:
FOR /f %%G in (D:\Users\krkarthi\Desktop\test1.txt)
DO
cscript D:\Users\krkarthi\Desktop\replace.vbs "D:\Users\krkarthi\Desktop\test.txt" "%%G" "#%%G"
Unfortunately, the above code didn't work at all. I don't understand where the error exists.
Try removing one % from the parameters in your code. It should work. Also you will not need double quotes while passing values to your code.
Corrected:
FOR /F %%G IN (D:\Users\krkarthi\Desktop\test1.txt) DO cscript D:\Users\krkarthi\Desktop\replace.vbs "D:\Users\krkarthi\Desktop\test.txt" "%%G" "#%%G"

Using variables in batch & VBS hybrids

This thread outlines how to code batch hybrids that may include a combination of several scripting languages, such as batch, VBS, JScript, PowerShell, etc. The question is, whether a batch hybrid treats "foreign" language blocks as "functions", meaning calls to these blocks may include arguments like regular and delayed expansion batch variables, that are referenced as usual arguments like %1, %2, etc?
Example below shows the approach in the task of unzipping a file, while using this file unzip code, but it gives an error in Win10 64-bit - why? Note, the linked file unzip code gives an error as well when run in Win 10, but a different one.
<!-- : Begin batch script
#echo off
set "dir=C:\Temp\" & set "file=%USERPROFILE%\Downloads\archive.zip\"
cscript //nologo "%~f0?.wsf" "%dir%" "%file%"
exit /b
----- Begin wsf script --->
<job><script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(%1) Then
fso.CreateFolder(%1)
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip = objShell.NameSpace(%2).items
objShell.NameSpace(%1).CopyHere(FilesInZip)
set fso = Nothing
set objShell = Nothing
</script></job>
:: Error
..\test.bat?.wsf(9, 8) Microsoft VBScript compilation error: Invalid character
In vbscript the first argument is : wscript.Arguments(0)
the second argument is : wscript.Arguments(1)
So,you should write it like that :
`
----- Begin wsf script --->
<job><script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(wscript.Arguments(0)) Then
fso.CreateFolder(wscript.Arguments(0))
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip = objShell.NameSpace(wscript.Arguments(1)).items
objShell.NameSpace(wscript.Arguments(0)).CopyHere(FilesInZip)
set fso = Nothing
set objShell = Nothing
</script></job>

Pin shortcut (.lnk) to start menu

I'm currently making an installation script by using a .cmd file.
Here is my code:
IF EXIST "%USERPROFILE%\Desktop\Opslag\Opslag.hta" (
START "" "%USERPROFILE%\Desktop\Opslag\Opslag.lnk" /secondary /minimized
MSG "%USERNAME%" The program is already installed.
EXIT
) ELSE (
XCOPY %SOURCE% %DESTINATION% /D /E /C /R /I /K /Y
START "" "%USERPROFILE%\Desktop\Opslag\Opslag.lnk" /secondary /minimized
MSG "%USERNAME%" Setup is complete!
EXIT
)
The %SOURCE% and %DESTINATION% are set earlier in the script.
When the folder has been copied I want the file %USERPROFILE%\Desktop\Opslag\Opslag.lnk to be added to the Start Menu.
I have seen earlier posts like:
How to pin to start menu using PowerShell, but I cannot make it work.
I'm currently testing it on my home laptop which runs Windows 7 with danish language. The machine where I need to do this runs Windows 7 with english language. Therefore I think the $verb is different from the scripts I've found, but I haven't tested on my work station.
Furthermore my work station has a very limited UAC,
and therefore I do not have Administrator rights. And please do not comment on how this should not be done by users, but only Administrators/IT, as I know what I'm doing.
I hope someone can help me pin the Opslag.lnk to the Start Menu, preferably on both languages (danish and english).
Find the location of the Start Menu folder:
For /f "tokens=3*" %%G in ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Start Menu" ^|Find "REG_"') do Call Set _startmenu=%%H
echo %_startmenu%
pause
In another search I stumbled across a very usefull VBScript: http://blogs.technet.com/b/deploymentguys/archive/2009/04/08/pin-items-to-the-start-menu-or-windows-7-taskbar-via-script.aspx:
Const CSIDL_COMMON_PROGRAMS = &H17
Const CSIDL_PROGRAMS = &H2
Set objShell = CreateObject("Shell.Application")
Set objAllUsersProgramsFolder = objShell.NameSpace(CSIDL_COMMON_PROGRAMS)
strAllUsersProgramsPath = objAllUsersProgramsFolder.Self.Path
Set objFolder = objShell.Namespace(strAllUsersProgramsPath & "\Accessories")
Set objFolderItem = objFolder.ParseName("Calculator.lnk")
Set colVerbs = objFolderItem.Verbs
For Each objVerb in colVerbs
Wscript.Echo objVerb
Next
The script lists alle the verbs for the specifik program, in this case the Calculator. Unfortunately the verb "Pin to Start Menu" in my Opslag.lnk is not listed, and therefore I do not think this can be done with verbs. Hope some one else has other ideas.
I used a .vbs to do this in the current profile (and used the registry, runonce to launch the .vbs on all (new)userprofiles). We are working with both Dutch and English devices in our company so you will see that it will try both languages. The problem is that it did not work on a .lnk but you can always create an exe referring to your desired destination.
Dim strFolder, strExecutable
Set objShell = CreateObject("Shell.Application")
strFolder = "C:\Tools"
strExecutable = "Tool.exe"
Set objFolder = objShell.Namespace(strFolder)
Set objFolderItem = objFolder.ParseName(strExecutable)
Set colVerbs = objFolderItem.Verbs
'Loop through the verbs and if PIN is found then 'DoIt' (execute)
blnOptionFound = False
For Each objVerb In colVerbs
If Replace(objVerb.name, "&", "") = "Aan het menu Start vastmaken" Then
objVerb.DoIt
blnOptionFound = True
End If
Next
For Each objVerb In colVerbs
If Replace(objVerb.name, "&", "") = "Pin to Start Menu" Then
objVerb.DoIt
blnOptionFound = True
End If
Next

batch script to delete and replace files in multiple locations

What I am looking to do is create a batch file to replace teh cert8.db file in a users application data folder as well as insert a line of text into one of the prefs.js file. Normally this would be easy, the issue is that there is a good chance some of my users have multiple firefox profiles so I would like to have a script to to replace all cert8.db files in the firefox/profiles folder and insert 1 line of next into all prefs.js files in the firefox/profiles folder.
Can this be done? I am willing to use vb if possible.
You could do something like this:
Set fso = CreateObject("Scripting.FileSystemObject")
profilesFolder = "C:\Users"
firefoxProfiles = "AppData\Roaming\Mozilla\Firefox\Profiles"
For Each fldr In fso.GetFolder(profilesFolder)
profilePath = fso.BuildPath(fldr.Path, firefoxAppdata)
If fso.FolderExists(profilePath) Then
For Each profile In fso.GetFolder(profilePath)
certdb = fso.BuildPath(profile, "cert8.db")
prefs = fso.BuildPath(profile, "prefs.js")
If fso.FileExists(certdb) Then
'replace cert8.db
End If
If fso.FileExists(prefs) Then
'modify prefs.js
End If
Next
End If
Next
The code for replacing the DB file and modifying the preferences depends on where the replacement DB comes from and what you want to add or update in the preferences.
FOR /D %%i IN (C:\Users\*.*) Do FOR /D %%j IN (%%i\AppData\Roaming\Mozilla\Firefox\Profiles\*.*) Do (
CALL :ReplaceDB "%%j\cert8.db"
CALL :ChangeJS "%%j\prefs.js"
)
:ReplaceDB
IF NOT EXIST %1 GOTO :EOF
MOVE /Y %1 "%~1.old"
COPY C:\firefox\cert8.db %1
GOTO :EOF
:ChangeJS
IF NOT EXIST %1 GOTO :EOF
ECHO user_pref("network.proxy.autoconfig_url", "pac.pe.lan/pac/proxy.pac") >> %1
GOTO :EOF
EDIT: Added second FOR to search profiles.
EDIT: Added code for replacing DB and appending line to JS.

Resources