1

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?

7
  • 2
    $Error[0] = $null will either result in an error or be ignored. Use try/catch/finally if you want to capture and suppress any exceptions raised by the [StreamWriter]::new call, and make sure to call $StreamWrite.Dispose() in the finally block to release the lock Commented Jun 1, 2023 at 11:06
  • 1
    Why not simply using the native PowerShell Add-Content cmdlet? Commented Jun 1, 2023 at 11:22
  • Also note that the problem may not be one of locking, but one of permissions, for instance. catch and log the exception to determine the actual cause. (As an aside: while $Error[0] = $null does work, it's better not to overwrite existing items in the $Error collection). Commented Jun 1, 2023 at 11:35
  • @ Mathias R. Jessen- Yes, I didn't mention that I have $StreamWrite.Close() and $StreamWrite.Dispose() at the end of my script. I've just edited my OP. Commented Jun 2, 2023 at 7:18
  • @iRon- I've tried "Write-Output "$TimeStamp" | out-file -FilePath $PathToTextFile -Append -Force" but this seems to overlook whether the file is already opened or not. Commented Jun 2, 2023 at 7:22

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.