多线程中的Powershell代码写入单个日志文件,但是由于文件正在使用而丢失了一些数据

时间:2016-10-21 16:20:59

标签: multithreading powershell logging

我在多线程中使用PowerShell代码写入单个日志文件,但由于文件正在使用,因此会丢失一些数据。有没有办法暂停线程,直到文件解锁?

螺纹输出语句:

LogWrite "$Server, $SEPVersion, $AVFileVersionDate, Revision $AVRevisionKey, $SylinkGroup, $Boottime, $UpTime"   

#Main script

$MaxThreads = 4
StartLog
$filename = Get-FileName
$filecontents = Get-Content $filename

foreach ($server in $servers) {
  Start-Job -Name $Server -ScriptBlock $scriptBlock -argumentlist $server 
  While($(Get-Job -State Running).Count -ge $MaxThreads) {
    Get-Job | Wait-Job -Any | Out-Null
  }
  Get-Job -State Completed | % {
    Receive-Job $_ -AutoRemoveJob -Wait
  }
}
While ($(Get-Job -State Running).Count -gt 0) {
  Get-Job | Wait-Job -Any | Out-Null
}
Get-Job -State Completed | % {
  Receive-Job $_ -AutoRemoveJob -Wait
}

1 个答案:

答案 0 :(得分:3)

更改日志记录功能,使其接受管道输入(有关参数的详细信息,请参阅about_Functions_Advanced_Parameters):

function LogWrite {
  Param(
    [Parameter(
      Mandatory=$true,
      ValueFromPipeline=$true,
      ValueFromPipelineByPropertyName=$true
    )]
    [string]$Message
  )

  ...
}

更改您的scriptblock,使其只是回显输出而不是写入文件。

然后将Receive-Job收集的输出传输到您的日志记录功能:

Get-Job -State Completed | Receive-Job -AutoRemoveJob -Wait | LogWrite

如果要在作业仍在运行时获取输出,可以在等待作业完成的循环中执行此操作:

While ($(Get-Job -State Running).Count -gt 0) {
  Get-Job | Receive-Job | LogWrite
  Start-Sleep -Milliseconds 200
}