i try to write a logfile with some debug output. My it runs fine with sequential runs, but as soon as i start the baseapplication in more instances, i get an error.
Der Prozess kann nicht auf die Datei zugreifen, da ein anderer Prozess einen Teil der Datei gesperrt hat. : 'B:\Logfiles\Startup.log' The process can not access the file because it is locked by another process.
So i tried to do a do - try - catch construct to retry if the file is locked. But for some reason this is not working:(
do{
$Failed = $false
Try{
Write-Output "C:\KFZBooth\Software\02_remove.bg\AIBackgroundRemove.exe" -ArgumentList '"batch"',`"$Original`",'""',`"$AIAusgabepfad\$Originaldatei$Originaltyp`" | Out-file $StartUpLog -append
} catch {
$Failed = $true
Write-Host "RETRY Reduce Credit"
Write-Host $_.Exception.Message
Write-Host $_.Exception.ItemName
Write-Output "Logproblem im Startup.log - RETRY" | Out-file $UsageLog -append
}
} while ($Failed)
Is there a better way of writing logfiles or wait for a file to be unlocked?
It really depends on the file type. for example, if you were logging using MSWord or other MSOffice files:
Run the code below with the file closed, and then the file opened.
Text files do not have this issue.
Yet, why use a file at all. Create your own event log and write directly to that.
Have you looked at using PowerShell transcripts?