ฉันสองวิธีแก้ปัญหาโดยบึง - กระดิก นี่เป็นเวอร์ชั่นสคริปต์ของฉัน:
# 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."
}
คุณสามารถโทรจาก cmd เช่นนี้:
powershell -ExecutionPolicy Unrestricted -file lock_file.ps1 "path\to\file_to_lock.txt"