[英]My script can read a text file when run manually through ISE, but it looks in a different directory when run through Task Scheduler
[英]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()
我在特定事件上通過 Task Scheduler 運行它,但它永遠不會退出循環,因為它會引發文件被另一個進程打開的錯誤。 但是當我逐行運行時,就沒有問題了。 我也可以在 Windows 瀏覽器中打開文本文件。 我錯過了什么?
這對於線程安全的 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)
以下是有效的,但 $StreamWrite 不是以獨占方式打開的(線程安全的):
do{
$Error.Clear()
$StreamWrite = [System.IO.StreamWriter]::new($PathToTextFile,$true,
[system.Text.Encoding]::Unicode)
}while ($Error.Count -gt 0)
$StreamWrite.WriteLine("$TimeStamp")
$StreamWrite.Close()
$StreamWrite.Dispose()
我還需要確保使用 Unicode 編碼打開文本文件。 我意識到我需要改用這種格式: StreamWriter(String, Encoding, FileStreamOptions)但我不確定如何構建 FileStreamOptions object。
到目前為止,這是我設法實現的目標,但我想添加編碼:
$FileStream= [System.IO.FileStream]::new($PathToTextFile,[System.IO.FileMode]::Append,[System.IO.FileAccess]::Write,[IO.FileShare]::None)
$StreamWrite = [System.IO.StreamWriter]::new($FileStream)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.