Powershell: Get-Content without locking file
I need to read a file on a remote pc which is frequently modified. As it so happens, it appears that my script is sometimes colliding with a write on the file, rendering it inaccessible. I cannot change the way the file is written to so I have to work with what I have.
I ran a test by having a script continuously reading a file with Get-Content and subsequently starting another script which writes to the file at frequent intervals. At times, the write operation was not possible.
Is it possible that I use get-content on a remote pc without locking the file?
[System.IO.FileStream]$fileStream = [System.IO.File]::Open("\\remote\share\Text Document.txt", [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
$byteArray = New-Object byte[] $fileStream.Length
$encoding = New-Object System.Text.UTF8Encoding $true
while ($fileStream.Read($byteArray, 0 , $byteArray.Length)) {
$encoding.GetString($byteArray)
}
$fileStream.Dispose()
The content that is being written cannot be read on the same time.
As a solution for you, you could read the file using shadow copy. For that, you will need to mount a shadow copy.
$s1 = (Get-WmiObject -List Win32_ShadowCopy).Create("X:\", "ClientAccessible")
$s2 = Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $s1.ShadowID }
$d = $s2.DeviceObject + "\" #
cmd /c mklink /d X:\tmpshacpy "$d"
After this, you can access the mounted location ( X:\tmpshacpy) and read the file just fine.
To unmount the shadow copy after the read is done, use $s2.Delete().