2

I am trying to use a text file for a lock mechanism.

The idea is that once the powershell script is running and holding the file handle, other processes will not be able to to open it and will wait until it released.

$file = [System.io.File]::Open('D:\file.lock', 'Open', 'Read', 'None')
$reader = New-Object System.IO.StreamReader($file)
$text = $reader.ReadToEnd()
$text | Out-File $file
$reader.Close()
$file.Close()

The locking is working well, however I want the once the script releases the file, it should do a 'touch' so the file's Last Modified Date will be changed

The problematic code of mine is $text | Out-File $file as it is not doing a thing

How can I save the file, or do a 'touch'

user829174
  • 6,132
  • 24
  • 75
  • 125

1 Answers1

7

this may be as easy as setting the lastwritetime manualy :

(ls $file).LastWriteTime=(get-date)

edit : you can use this (but can't read the file content as we open it for writing )

$file = [System.io.File]::Open('c:\temp\test.txt', 'append', 'Write', 'None')
$enc = [system.Text.Encoding]::UTF8
$msg = "This is a test" 
$data = $enc.GetBytes($msg) 
$file.write($data,0,$data.length)
$file.Close()
Loïc MICHEL
  • 24,935
  • 9
  • 74
  • 103
  • It is working when I run this command only, however I want it to happen after I open the file and before closing it. it is not changing it. – user829174 Oct 02 '14 at 08:20
  • 1
    did you try to change the acces mode to readwrite : `$file = [System.io.File]::Open('D:\file.lock', 'Open', 'ReadWrite', 'None')` – Loïc MICHEL Oct 02 '14 at 08:33