andreaspfr
andreaspfr

Reputation: 2314

LastWriteTime of a shared file in Powershell

I would like to get the last write time of a txt file which is located in a shared folder. I write the last write time in an other file. The problem is that I'm always getting an odd DateTime ("Sunday, December 31, 1600 4:00:00 PM"). I found this description in the MSDN : "If the file described in the FileSystemInfo object does not exist, this property will return 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time." To check whether I can access from the file I loaded something out of this file and it works. Therefore my file exists. If I apply my program on a local drive I'm getting right dates. The following code represent my program:

$SharedFolder = "\\SharedFolder"


new-psdrive -name Z -psprovider FileSystem -root $SharedFolder
$usersFileName = "Z:\users.txt"
$file = New-object System.IO.FileInfo $usersFileName
$tempDate = $file.LastWriteTime


while($true){

        $file2 = New-object System.IO.FileInfo $usersFileName       
                $tempDate2 = $file2.LastWriteTime

        if($tempDate -ne $tempDate2)

                {
            $name ="ahs been changed"
            $Name | out-file C:\users\test\desktop\test2.txt -append
            $file = New-object System.IO.FileInfo $usersFileName
                        $tempDate = $file.LastWriteTime
                }
        $tempDate | out-file C:\users\test\desktop\test2.txt -append
        Start-sleep -s 2
}

Upvotes: 0

Views: 1338

Answers (1)

manojlds
manojlds

Reputation: 301637

Instead of doing

$file = New-object System.IO.FileInfo $usersFileName

You can just do

$file = get-item $usersFileName

Then you can still do $file.LastWriteTime and get the proper time.

I think creating a FileInfo object by yourself doesn't work because the PsDrive might not be known to the .Net method, and eventhough that is what Get-Item returns, it is able to handle it internally. Note that creating the object by yourself with the share path, does give right time, so it is not an issue with share, but with the PsDrive.

Also, you need not create objects again and again and then check on the FileInfo. You can just call the Refresh method. This is the same with Get-Item. You can just call Refresh to get the updated times.

And btw, you seem to be watching modifications to a file and logging it. .Net and Powershell ( through eventing etc.) have great support for doing such things. Have a look at FileSystemWatcher ( http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx )

Upvotes: 1

Related Questions