Last active
August 14, 2023 23:19
-
-
Save sgornick/d6072ef254bfe58f18ffd53b78ae0e7a to your computer and use it in GitHub Desktop.
Hold a file open exclusively, not even accessible for reading (PowerShell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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