我正在嘗試使用路徑變數在 Start-job 腳本塊中啟動程式。這是行:
$using:plinkdir\plink.exe -telnet $using:ip -P $using:port | TimeStamp >> "$using:LogDir\WeightLog_$(get-date -f MM-dd-yyyy).txt"
所有變數都有效,當我使用 c:\plink 代替 $plink 變數時,整行有效。它在 -telnet 上出錯,因此沒有得到 plink 的引數。
這是 $var 和作業:
$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 {
# Bring Variables into job from callers scope
#$LogDir = $using:LogDir
#$PlinkDir = $using:PlinkDir
#$SerialIP = $using:SerialIP
#$SerialPort = $using:SerialPort
# Set TimeStamp format
filter timestamp {"$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_"}
# Start plink, pipe output to TimeStamp, redirect to log file
$using:PlinkDir\plink.exe -telnet $using:SerialIP -P $using:SerialPort | TimeStamp >> "$using:LogDir\WeightLog_$(get-date -f MM-dd-yyyy).txt"
}
}
謝謝!
uj5u.com熱心網友回復:
該答案基于一些假設以及對您的問題和評論中解釋的內容可能有用的預感。
首先,解釋一下“PowerShell被意外殺死時它沒有丟失任何資料”。,這是因為>>(別名Out-File -Append)是:
- 打開檔案流
- 將輸出附加到檔案
- 關閉流
所以,當你殺死作業時,基本上還在那里。我確實建議您使用Set-Content,但這是在我了解您在做什么之前,在這種情況下,這不是一個選擇。
這里提出的替代方案是使用StreamWriter,這很好,因為我們可以保持檔案流打開并根據需要附加到檔案,而無需每次都關閉流(這也將處理“每行之間的空白行”輸出到日志檔案”)。為了避免殺死 Job 但仍將結果保存到檔案中,我們可以使用try / finally陳述句。
$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?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472102.html
下一篇:for回圈的輸出串列作為變數
