I second the solution by marsh-wiggle. Here's my version of the script:
# This is lock_file.ps1
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$my_file_path
)
if (!$my_file_path){
Write-Host "Parameter my_file_path is missing, quitting."
[Environment]::Exit(1)
}
$my_file_exists = Test-Path $my_file_path -pathType Leaf
If ($my_file_exists) {
#Open the file in read only mode, without sharing (I.e., locked as requested)
$my_open_file = [System.io.File]::Open($my_file_path, 'Open', 'Read', 'None')
#Wait in the above (file locked) state until the user presses a key
Write-Host "Press any key to continue ..."
$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#Close the file
$my_open_file.Close()
} else {
Write-Host "Parameter mismatch, file doesn't exist."
}
You can call it from cmd like this:
powershell -ExecutionPolicy Unrestricted -file lock_file.ps1 "path\to\file_to_lock.txt"
Apparently, editors such as Notepad and Notepad++ don't even keep the file open non-exclusively. – John – 2014-08-27T15:31:42.000
Why not just make one? Also, how long should they hold the lock? Should they wait for some event? – user541686 – 2011-06-09T02:38:23.387
6
I considered programming one but figured there's a quick tool, editor or command I can use. On superuser not all users are programmers. http://bit.ly/lXT6ey I didn't want to go the Stackoverflow route with this question. Am testing the behaviour of an app when it can't access files.
– John K – 2011-06-09T02:53:20.433I might be able to make one for you -- just lemme know when the lock should be released. – user541686 – 2011-06-09T02:57:59.090
see also my similar question http://superuser.com/questions/519389/flock-command-for-windows
– eadmaster – 2012-12-18T02:50:18.567