試圖弄清楚如何忽略或停止使用 StreamWriter 將特定行寫入檔案。這是我正在使用的代碼,來自How to pass arguments to program when using variable as path:
$LogDir = "c:\users\user" # Log file output directory
$PlinkDir = "C:" # plink.exe directory
$SerialIP = "1.1.1.1" # serial device IP address
$SerialPort = 10000 # port to log
function CaptureWeight {
Start-Job -Name WeightLog -ScriptBlock {
filter timestamp {
$sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
}
try {
$sw = [System.IO.StreamWriter]::new("$using:LogDir\WeightLog_$(Get-Date -f MM-dd-yyyy).txt")
& "$using:PlinkDir\plink.exe" -telnet $using:SerialIP -P $using:SerialPort | TimeStamp
}
finally {
$sw.ForEach('Flush')
$sw.ForEach('Dispose')
}
}
}
$job = CaptureWeight # For testing, save the job
Start-Sleep -Seconds 60 # wait 1 minute
$job | Stop-Job # kill the job
Get-Content "$LogDir\WeightLog_$(Get-Date -f MM-dd-yyyy).txt" # Did it work?
輸出是這樣的:
05/09/2022_14:34:19 G 027800 lb
05/09/2022_14:34:20
05/09/2022_14:34:20 G 027820 lb
05/09/2022_14:34:21
05/09/2022_14:34:21 G 027820 lb
05/09/2022_14:34:22
05/09/2022_14:34:22 G 027820 lb
沒有時間戳,每隔一行都是空白的。我有幾行來清理日志,一個洗掉每隔一行,一個洗掉權重為零的行:
Set-Content -Path "$LogDir\WeightLog_$(get-date -f MM-dd-yyyy).txt" -Value (get-content -Path "$LogDir\WeightLog_$(get-date -f MM-dd-yyyy).txt" | Where-Object { $i % 2 -eq 0; $i })
Set-Content -Path "$LogDir\WeightLog_$(get-date -f MM-dd-yyyy).txt" -Value (get-content -Path "$LogDir\WeightLog_$(get-date -f MM-dd-yyyy).txt" | Select-String -Pattern '00000' -NotMatch)
如果檔案變得太大,這些可能需要一段時間才能運行,最好不要從一開始就撰寫它們。
謝謝!
uj5u.com熱心網友回復:
如果我理解正確,添加此條件應該可以避免您不得不閱讀日志并跳過不需要的行的麻煩。
有關詳細資訊,請參閱String.IsNullOrWhiteSpace(String)方法和-match匹配運算子。
filter timestamp {
# if this output is purely whitespace or it matches `00000`
if([string]::IsNullOrWhiteSpace($_) -or $_ -match '00000') {
# skip it
return
}
$sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
}
關于上一個問題中提到的觀察:
...在檔案運行時嘗試查看檔案時,似乎它大約每 2 分鐘更新一次(用于查看),您會得到一個 2 分鐘的資料塊,該資料塊大約落后 2 分鐘,2 分鐘的資料就在那里.. .
為此,您可以AutoFlush從StreamWriter.
Remarks很好地解釋了何時值得啟用此屬性以及性能影響:
當
AutoFlush設定為 時false,StreamWriter 將在內部和可能在編碼器中從您傳入的編碼中進行有限的緩沖。您可以通過設定AutoFlush為獲得更好的性能false,假設您總是呼叫Close(或至少Flush)當你'用 StreamWriter 重新完成寫入。
例如,設定
AutoFlush為true當您寫入用戶期望立即反饋的設備時。Console.Out是其中一種情況:內部用于寫入 Console 的 StreamWriter 在每次呼叫StreamWriter.Write.
$sw = [System.IO.StreamWriter]::new("$using:LogDir\WeightLog_$(Get-Date -f MM-dd-yyyy).txt")
$sw.AutoFlush = $true
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/472130.html
標籤:电源外壳 流作家 streamwriter.write
