• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 875
  • Last Modified:

Need a Script to change the file 'Date Modifed' to current date.

Hi all,

I have bunch of files across some foldres. I need to touch those files, i.e. i want to change the accessed/modifed date for those files.

The logic would be like.

declare a array variable to hold the file names
loop thorugh each file name
change the modification to the current date

I don't know VBScript and looking for solution in VBScript.
The fles/folders are on Windows enviroment.If this is possible in JavaScript or any other scripting language with simple double click on the .vbs etc file, that is fine for me.

This is little bit urgent. Please help me.
0
Sharath
Asked:
Sharath
  • 12
  • 8
  • 2
2 Solutions
 
Tompa99Commented:
Hi there

I don't have a complete solution for you but to change ModifyDate from a vbscript on a file
this is one way to do it on.

Regards Tompa
strDir = "c:\temp\"
strFileName = "test.txt"
 
 
RunCommand = ChangeModifyDate(strDir,strFileName)
 
Function ChangeModifyDate(strDir, strFileName )
    Dim ObjShell
	Dim ObjFolder
    
    Set ObjShell = CreateObject("Shell.Application")
    Set ObjFolder = ObjShell.NameSpace(strDir)
    ObjFolder.Items.Item(strFileName).ModifyDate = now
End Function

Open in new window

0
 
SharathData EngineerAuthor Commented:
Thanks Tompa99, but i need to a complete script. Is it possible to provide the loop also?
0
 
Tompa99Commented:
Hi
Well didn't find a better solution on how to handle the file list in a easy way.
But I did the following created a text file Files.txt added two rows like the follwing:
c:\temp\;test.txt
c:\dev\;test1.txt;test2.txt

The file is separated with char ; and the first column is the folder path and the rest of the columns are the files you want to change date on. Is this a solution that could work?

Regards Tompa

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
 
Dim objFso, DataFile, DataFilePath
DataFilePath = "c:\dev\files.txt" ' Path for File with all folders and files to change
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
set DataFile = objFso.OpenTextFile(DataFilePath, ForReading)
 
Do Until DataFile.AtEndOfStream
    strNextLine = DataFile.Readline
    arrayFileList = Split(strNextLine , ";")
    For i = 1 to Ubound(arrayFileList)
		RunCommand = ChangeModifyDate(arrayFileList(0),arrayFileList(i))		        
    Next
Loop 
 
Function ChangeModifyDate(strDir, strFileName )
    Dim ObjShell
        Dim ObjFolder
    
    Set ObjShell = CreateObject("Shell.Application")
    Set ObjFolder = ObjShell.NameSpace(strDir)
    ObjFolder.Items.Item(strFileName).ModifyDate = now
 
End Function

Open in new window

0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
SharathData EngineerAuthor Commented:
Thanks Tompa. But i didn't find array declaration (something like that) in your solution. I want to declare all my file names and want to loop them. Please note that I have files in many folders, not one folder.
0
 
SharathData EngineerAuthor Commented:
raised points
0
 
SharathData EngineerAuthor Commented:
I will explain my problem better:
I have some flat files on a server( Windows OS only). Those files will be bulk inserted into my staging db. But before bulk inserting the files will be validated for the last modifed date. If the files are modifed within certain time (last 1 hour or 2 hours etc), then only the files are proecessed otherwise skipped. Now I want to touch those files before running my ETL so that no file will be skipped.
The problem is how to touch (modify the last accessed time) those files? I cannot open each and every file and save (to change the last modified time). I want to automate this process. Any solution (either a VBScript or JavaScript or T-SQL) is helpful to me.
Moderator - Could you look into this question and alert the experts for more attention.
 
0
 
Mark WillsTopic AdvisorCommented:
Can do this in T-SQL...

In the update statement, make sure you change the convert style number for filedate.

You could also use a dir /t:a *.txt  if you wanted to then unpack that line. The /t:a means last accessed date.

Here, we use a ' ## ' as a delimiter between filename and filedate. Can change that if needed...

Then can loop through that list visiting / processing each file as needed.

Let me know if we are on the right track...


if object_id('tmp_files_list','u') is not null drop table tmp_files_list
 
create table tmp_files_list(files varchar(200), diskfilename varchar(100), filedate datetime)
 
insert tmp_files_list (files)
exec xp_cmdshell 'for %i in (c:\ee\*.txt) do @echo %~fi ## %~ti '
 
update tmp_files_list set diskfilename = substring(files,1,charindex(' ## ',files)),
                           filedate = convert(datetime,substring(files,charindex(' ## ',files)+4, len(files)),103)
where files like '% ## %'
 
select diskfilename, filedate from tmp_files_list where diskfilename is not null

Open in new window

0
 
SharathData EngineerAuthor Commented:
thanks mark. will try it tomorrow.
0
 
SharathData EngineerAuthor Commented:

Mark - i think you didn't understand my requirement clearly. I want to change the 'Date Modifed' attribute for the file.
Here you are reading the file name, date modifed and inserting into a temp table.
However i am getting date varchar to datetime conversion error. (forget about this error. I can handle. but this is not what i want.)
0
 
Mark WillsTopic AdvisorCommented:
Sorry about that. Yep you are correct, did not read the question properly. Thought you wanted a list of files for import into a staging table...

Will give some more thought... Probably OA procedures - have one that can read and write, not sure about set date property...
0
 
Mark WillsTopic AdvisorCommented:
OK, we can get the list of files from the above, and to set "LastAccessed" can easily do :


declare @FileSystem int,
        @status int,
        @FileID int
 
EXECUTE @status = sp_OACreate 'Scripting.FileSystemObject', @FileSystem OUT
IF @status <> 0 PRINT 'Scripting.FileSystemObject'
 
--Open a file
EXECUTE @status = sp_OAMethod @FileSystem, 'OpenTextFile', @FileID OUT, 'c:\ee\MyDocument.txt', 8, 0              -- 1=read,2=write,8=Append; 0=don't create,1=docreate
IF @status <> 0 PRINT 'OpenTextFile'
 
--execute @status = sp_OAMethod @FileID, 'WriteLine', Null, Null                     -- if you write NULL to the file it will change the lastmodifieddate
--IF @status <> 0 PRINT 'Write NULLs'
 
execute @status = sp_OAMethod @FileID, 'Close'
IF @status <> 0 PRINT 'Close'
 
EXECUTE @status = sp_OADestroy @FileID
IF @status <> 0 PRINT 'OpenTextFile'

Open in new window

0
 
Mark WillsTopic AdvisorCommented:
If you are getting into Windows Powershell, there is a very cool script you can run :

http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb07/hey0213.mspx
0
 
SharathData EngineerAuthor Commented:
Thanks Mark for the script and the link. The script is working fine. I have tuned it according to my requirement. However as you see, its appending one NULL row in the text file. So I am ended up with a NULL row in my file. every time i ran the script, i am getting (appending) one NULL row. how can i handle this? i.e. after appending NULL record, just want to remvove that row. (last row in my text file)?
0
 
Mark WillsTopic AdvisorCommented:
Is it the last accessed date or the last modified date ? If you can use the last accessed date, then do not do the write line.

The OA procedures can only access datelastmodified as a read only property.

To get a list of files using last accessed date do a dir /T:A *.txt   and it will then use the last accessed date in a DIR command.

Otherwise, you need to go to some "real" code and use one of the Windows API's to change the date.

Have included a ZIP file. Unzip the three files and remove the additional .txt extensions. Either put the files into an existing path, or keep together whereever you are going to run the exe from.

Simple command line utility : touch -m filename

That will update the modified date (denoted by -m) of the filename. And that filename can include wildcards. Grabbed it from GNU many years back and still works on my XP Pro machine, so do not see why it wouldn't work on other WIN platforms.


GNU (origin of 'touch.exe') : http://gnuwin32.sourceforge.net/

CodeProject Source Code :  http://www.codeproject.com/KB/applications/touch_win.aspx

or C# code as a console project from a posting by "RON" on http://www.online-tech-tips.com/computer-tips/how-to-change-the-last-modified-date-creation-date-and-last-accessed-date-for-files-and-folders/ :









using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace touch
{
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
 
if (args.Length == 0)
{
Console.WriteLine(String.Format(\{0}\", dt.ToString()));
return;
}
 
if (args[0].Contains(?) || args[0].Contains(help))
{
Console.WriteLine(touch usage: \r\n touch -> no arguments returns current date time\r\ntouch path -> sets all files (recursively) under path to current time\r\ntouch sets all files in path to where time is any time format parseable);
return;
}
 
if (args.Length > 1)
{
DateTime.Parse(args[1]);
}
 
String FileSpec = args[0];
 
DirectoryInfo di = new DirectoryInfo(FileSpec);
 
FileInfo [] fi = di.GetFiles(*.*, SearchOption.AllDirectories);
 
foreach (FileInfo file in fi)
{
file.CreationTime = dt;
file.LastAccessTime = dt;
file.LastWriteTime = dt;
} 
 
Console.WriteLine(String.Format(Changed File Time on {0} files, fi.Length));
}
}
}

Open in new window

touch.zip
0
 
SharathData EngineerAuthor Commented:

I think i didn't explain you properly. Whatever the "Date Modified" for a file, i want to touch it. thats it. I have folder strcture and files. Using your script (Post# 24225640),I am able to pass the filename (full path) and change the "Date Modifed". (because you are writing a NULL row into the file).
after writing this NULL row, could you tell me to delete it. So that i will be having my original file without the extra NULL row at the end.
Yet to look into to your attachments and the script in your last post.
Thanks again.
0
 
Mark WillsTopic AdvisorCommented:
Yep, now understand.

That last post replaces the previous use of OA. Now resorted to "real code" and there is an EXE and two DLL in that zip.

make a folder c:\ee\touch

unzip the touch.zip file into that folder and remove the fake .txt extension on those three files

copy some other files into it.

check date modified in windows explorer.

click start then run then cmd

at the command prompt type cd c:\ee\touch

then touch -m *.*

then have a look in file explorer again for the date modified property.

Think that is what you are asking for.

From SQL, can use that command, or, can set up a batch job.
0
 
SharathData EngineerAuthor Commented:
Is it possible to modify the Post (# 24225640) little bit as per my requirement (deleting the newly appended last NULL row)? I tried your last suggestion but no luck. As I am a SQL guy and we are already in the middle with OLE object script, i think we can do this in SQL. I am confirtable using SQL than dlls or batch files.    
0
 
SharathData EngineerAuthor Commented:

To be more specific,
as you are writing NULL row with "WriteLine", I am looking for similar code with paramter like "DeleteLine" or "DeleteLastLine"
execute @status = sp_OAMethod @FileID, 'WriteLine', Null, Null
-- if you write NULL to the file it will change the lastmodifieddate
IF @status <> 0 PRINT 'Write NULLs'
0
 
Mark WillsTopic AdvisorCommented:
Alas, there is no deleteline...

There might be something else, will hunt around a bit more in my toy box :)

0
 
SharathData EngineerAuthor Commented:
i know that there is no deleteline. (I googled a lot for that or something like that).  if there is any option like that, it would be good.
0
 
Mark WillsTopic AdvisorCommented:
We could do something like rename and write a new one. But that is fairly drastic considering the "touch" routine can already change the modified date.

this is what we got so far :

1) SQL Routine using cmdshell that gets a list of tablenames and date created
2) SQL Routine using OA processes to change Last Accessed Date
3) TOUCH.EXE program that changes the datelastmodified property - which we can do as per 1 above
4) Maybe a routine to rename/ write or copy to a new version using OA processes
5) Maybe create the console program in the earlier posting as a managed DLL code and use that in a CLR procedure

So, maybe a more lateral approach ? What is it about changing the date that becomes so vital - why do we need to recognise (or enforce) the change of datelastmodified date as opposed to either datelastaccessed or even datecreated ?  We could probably pick up either of those other dates, or, use the touch program, or even keep a local register in the database.

0
 
SharathData EngineerAuthor Commented:
in all these i am more interested on OA processes. If possible, i can go for xp_cmdshell. I am more interested in implementing this in T-SQL rather than DLLs or any other. Initially i thought that its not possible in SQL so choose VBScript. I really appreciate your efforts here. Why I am preferring T-SQL is i can fine tune it to my requirement. (the only thing is i need to get that logic). My requirement is with datemodifed only.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 12
  • 8
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now