英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论