Skip to content

Instantly share code, notes, and snippets.

@sgornick
Last active August 14, 2023 23:19
Show Gist options
  • Save sgornick/d6072ef254bfe58f18ffd53b78ae0e7a to your computer and use it in GitHub Desktop.
Save sgornick/d6072ef254bfe58f18ffd53b78ae0e7a to your computer and use it in GitHub Desktop.
Hold a file open exclusively, not even accessible for reading (PowerShell)
# Open the file in exclusive mode
while ($true) {
try {
$filenameAndPath = Read-Host "Enter filename and path for the file to hold open exclusively"
if ([string]::IsNullOrEmpty($filenameAndPath)) {
Write-Host "No filename was entered. Please provide a valid filename."
continue
}
if (-not [System.IO.Path]::IsPathRooted($filenameAndPath)) {
$filenameAndPath = [System.IO.Path]::GetFullPath($filenameAndPath)
}
if (Test-Path $filenameAndPath -PathType Container) {
Write-Host "$filenameAndPath is a directory. Please provide a valid filename."
continue
}
if (-not (Test-Path $filenameAndPath -PathType leaf)) {
Write-Host "File not found. Please provide a valid filename."
continue
}
break
}
catch [System.IO.FileNotFoundException] {
Write-Host "File not found. Please provide a valid filename."
}
catch [System.Management.Automation.PipelineStoppedException] {
Write-Host ""
Write-Host "Keyboard interrupt. Exiting..."
exit
}
}
try {
$fileStream = New-Object System.IO.FileStream($filenameAndPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::None)
try {
Write-Host ""
Write-Host "Holding open, exclusively: $filenameAndPath"
Read-Host "Press enter to continue..."
}
finally {
$fileStream.Close()
}
}
catch [System.IO.IOException] {
Write-Host "Error opening file: File is already in use."
exit 1
}
@sgornick
Copy link
Author

sgornick commented Aug 14, 2023

The "easy" methods to lock a file exclusively (like doing the command C:> Pause > test.txt ), still permit reading. This script is mean to lock the file exclusively and prevent even reading.

For the equivalent of this script, but in Python see:

https://gist.github.com/sgornick/6acb6974370da98f3b3c578d780c0728

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment