Powershell: Get-Content without locking file

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().


[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()