powershelllockingstreamwriter

Text file is locked for openning when running the script but I can open it manually


I have the following PowerShell script:

do{
    $Error[0]= $null
    $StreamWrite = [System.IO.StreamWriter]::new($PathToTextFile,$true,[system.Text.Encoding]::Unicode)
    
 }while ($Error[0] -ne $null)
$StreamWrite.WriteLine("$TimeStamp")
$StreamWrite.Close()
$StreamWrite.Dispose() 


I run this through Task Scheduler on specific events, but it never gets out of the loop as it raises the error of the file is open by another process. But when I run it line by line, there's no problem. I can also open the text file in Windows browser. What am I missing?


Solution

  • This works as a good solution for thread-safe StreamWrite and encoding:

    do{
        $Error.Clear()  
        
        $FileStream= [System.IO.FileStream]::new($PathToTextFile,[System.IO.FileMode]::Append,[System.IO.FileAccess]::Write,[IO.FileShare]::None)
        $StreamWrite = [System.IO.StreamWriter]::new($FileStream,[system.Text.Encoding]::Unicode)
        
     }while ($Error.Count -gt 0)