When you are working in an infrastructure and want to gather information from multiple machines in a single file, somewhere on a sharepoint, you will encounter a major problem, and that is that you can’t write in a file from multiple machines at the same time. Even on your own machine, if a file has a writing operation from one application and you try to write to it from another application, this will result in an error.
Let’s say i have a file called Information.txt on the Desktop, and I have the next PowerShell script which writes into it:
for($i=1;$i -le 10000; $i++){ Add-Content -Path "C:\Users\YOURUSER\Desktop\Information.txt" -Value "hello" }
function Check-FileOpen { param ( [parameter(Mandatory=$true)] [string]$Path ) $oFile = New-Object System.IO.FileInfo $Path if ((Test-Path -Path $Path) -eq $false) { $false return } try { $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($oStream) { $oStream.Close() } $false } catch { # file is locked by a process. $true } } while ((Check-FileOpen -Path "C:\Users\theje\Desktop\Information.txt")){ Start-Sleep -s 15 Write-Host "File in Use" } Write-Host "File Not in Use" Add-Content -Path "C:\Users\YOURUSER\Desktop\Information.txt" -Value "File Is Closed"