[英]Powershell: exclusive lock for a file during multiple set-content and get-content operations
我正在尝试编写一个脚本,该脚本在多台客户端计算机上运行并写入网络共享上的单个文本文件。
我想确保在任何时候只有一台机器可以操作文件,而其他机器运行一个循环来检查文件是否可用。
该脚本首先运行:
Set-Content -Path $PathToHost -Value (get-content -Path $PathToHost | Select-String -Pattern "$HostName " -NotMatch) -ErrorAction Stop
如果它们符合条件,则删除一些行。 然后我想添加一个新行:
Add-Content $PathToHost "$heartbeat$_" -ErrorAction Stop
问题在于,在执行这两个命令之间,另一个客户端可以访问该文件并开始写入该文件。
我在这里探索了解决方案: 在 PowerShell 中写入时锁定文件
$PathToHost = "C:\file.txt"
$mode = "Open"
$access = "ReadWrite"
$share = "None"
$file = [System.IO.File]::Open($path, $mode, $access, $share)
$file.close()
这绝对可以锁定文件,但我不确定如何继续读取和写入文件。
任何帮助深表感谢。
编辑:由于 twinlakes 的回答,解决方案如下
$path = "C:\Users\daniel_mladenov\hostsTEST.txt"
$mode = "Open"
$access = "ReadWrite"
$share = "none"
$file = [System.IO.File]::Open($path, $mode, $access, $share)
$fileread = [System.IO.StreamReader]::new($file, [Text.Encoding]::UTF8)
# Counts number of lines in file
$imax=0
while ($fileread.ReadLine() -ne $null){
$imax++
}
echo $imax
#resets read position to beginning
$fileread.basestream.position = 0
#reads content of whole file and discards mathching lines
$content=@()
for ($i=0; $i -lt $imax; $i++){
$ContentLine = $fileread.ReadLine()
If($ContentLine -notmatch "$HostIP\s" -and $ContentLine -notmatch "$HostName\s"){
$content += $ContentLine
}
}
echo $content
#Writes remaining lines back to file
$filewrite = [System.IO.StreamWriter]::new($file)
$filewrite.basestream.position = 0
for ($i=0; $i -lt $content.length; $i++){
$filewrite.WriteLine($content[$i])
}
$filewrite.WriteLine($heartbeat)
$filewrite.Flush()
$file.SetLength($file.Position) #trims file to the content which has been written, discarding any content past that point
$file.close()
$file
是一个 System.IO.FileStream 对象。 您将需要对该对象调用write方法,该方法需要一个字节数组。
$string = # the string to write to the file
$bytes = [Text.Encoding]::UTF8.GetBytes($string)
$file.Write($bytes, 0, $bytes.Length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.