简体   繁体   English

Powershell:在多个 set-content 和 get-content 操作期间对文件的独占锁定

[英]Powershell: exclusive lock for a file during multiple set-content and get-content operations

I am trying to write a script which runs on multiple client machines and writes to a single text file on a network share.我正在尝试编写一个脚本,该脚本在多台客户端计算机上运行并写入网络共享上的单个文本文件。

I want to ensure that only one machine can maniputale the file at any one time, whilst the other machines run a loop to check if the file is available.我想确保在任何时候只有一台机器可以操作文件,而其他机器运行一个循环来检查文件是否可用。

the script runs this first:该脚本首先运行:

Set-Content -Path $PathToHost -Value (get-content -Path $PathToHost | Select-String -Pattern "$HostName " -NotMatch) -ErrorAction Stop

Which removes some lines if they are matching the criteria.如果它们符合条件,则删除一些行。 Then I want to append a new line with this:然后我想添加一个新行:

Add-Content $PathToHost "$heartbeat$_" -ErrorAction Stop

The problem is that between the execution of those two commands another client has access to the file and begins to write to the file as well.问题在于,在执行这两个命令之间,另一个客户端可以访问该文件并开始写入该文件。

I have explored the solution here: Locking the file while writing in PowerShell我在这里探索了解决方案: 在 PowerShell 中写入时锁定文件

$PathToHost = "C:\file.txt"
$mode = "Open"
$access = "ReadWrite"
$share = "None"

$file = [System.IO.File]::Open($path, $mode, $access, $share)
$file.close()

Which can definitely lock the file, but I am not sure how to proceed to then read and write to the file.这绝对可以锁定文件,但我不确定如何继续读取和写入文件。

Any help is much appreciated.任何帮助深表感谢。

EDIT: Solution as below thanks to twinlakes' answer编辑:由于 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 is a System.IO.FileStream object. $file是一个 System.IO.FileStream 对象。 You will need to call the write method on that object, which requires a byte array.您将需要对该对象调用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.

相关问题 Powershell获取内容,使用数组进行过滤,然后设置内容 - Powershell Get-Content, filter with ARRAY, and then set-content 设置内容,然后获取内容以某种方式更改内容 - Set-Content and then Get-Content change the content somehow 如何在PowerShell v2中匹配和替换Get-Content和Set-Content对象中的字符串? - How to match and replace strings within Get-Content and Set-Content objects in PowerShell v2? 为什么在 PowerShell 的 Get-Content、Regex 和 Set-Content 之后所有换行符都消失了? - Why are all newlines gone after PowerShell's Get-Content, Regex, and Set-Content? POWERSHELL ISE批量/批量选择以进行编码转换(获取内容和设置内容) - POWERSHELL ISE Bulk/Batch select for encoding conversion (Get-Content & Set-Content) 使用 powershell Get-Content 和 Set-Content 编辑文本文件时遇到问题 - Trouble editing text files with powershell Get-Content and Set-Content Get-Content和Set-Content用特定的行分开 - Get-Content and Set-Content with specific lines and seperated 为什么 [IO.File]::WriteAllText 连接 Get-Content -tail ## output,而 Set-Content 没有? - Why does [IO.File]::WriteAllText concatenate the Get-Content -tail ## output, and Set-Content does not? 在Powershell中获取文件的内容 - Get-Content of a file in powershell Powershell 设置内容为空文件时出错 - Powershell Set-Content empty file on error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM