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?
$Error[0] = $nullwill either result in an error or be ignored. Usetry/catch/finallyif you want to capture and suppress any exceptions raised by the[StreamWriter]::newcall, and make sure to call$StreamWrite.Dispose()in thefinallyblock to release the lockAdd-Contentcmdlet?catchand log the exception to determine the actual cause. (As an aside: while$Error[0] = $nulldoes work, it's better not to overwrite existing items in the$Errorcollection).