文本文件在运行脚本时被锁定,但我可以手动打开它。

huangapple go评论47阅读模式
英文:

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

问题

我有以下的PowerShell脚本:

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() 

我通过任务计划程序在特定事件上运行它,但它永远不会跳出循环,因为它引发了文件被另一个进程打开的错误。
但是当我逐行运行它时,就没有问题。我也可以在Windows浏览器中打开文本文件。
我漏掉了什么?

英文:

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?

答案1

得分: 1

这是一个用于线程安全的StreamWrite和编码的良好解决方案:

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)
英文:

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)

huangapple
  • 本文由 发表于 2023年6月1日 18:56:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定