PowerShell: Start-Job -scriptblock Multi line scriptblocks?

不羁的心 提交于 2019-12-10 21:03:37

问题


Hoping someone can help me to figure out if this is possible. I have a 20 ish lines that scan a log file in a while loop. I need this to happen in parallel with the rest of the script. The log scanning loop is passing the entries into SQLite and other scripts need to act on this information - hence wanting to run them in parallel.

If i use the Job-Start command then it seems the -SciptBlock function will only accept one piped line of commands. I have too many commands to want to pipe so i need to run multiple lines in the scriptblock.

I tried several ways of doing it but the following examples give the least errors. I also tried it in an Invoke-Command -ScriptBlock -as job like in the second example - both ways will not accept a multiline scriptblock.

what am i doing wrong, please?

Start-Job -Name LogScan -ScriptBlock
{
  $EventOld = ConvertFrom-Json (Get-content ( Get-ChildItem  | Sort-Object -Property LastWriteTime | Select-Object -last 1 ) | Select-Object -last 1) 
  $RunLoop = 1
  while (RunLoop -ge 1)
    {
    Start-Sleep -Milliseconds 333
    $RunLoop = $RunLoop +1
    $EventNew = ConvertFrom-Json (Get-content ( Get-ChildItem  | Sort-Object -Property LastWriteTime | Select-Object -last 1 ) | Select-Object -last 1)
    if ($EventOld.timestamp -ne $EventNew.timestamp)
      {
         # lots of commands and here passing the array to SQLite
      }
    $EventOld = $EventNew
  }
}

Error is as follows:

Start-Job : Missing an argument for parameter 'ScriptBlock'. 
Specify a parameter of type 'System.Management.Automation.ScriptBlock' 
and try again. [..]

回答1:


Kudos to briantist for helping me to get there :)

When using Start-Job and Invoke-Command, be careful to put the opening { for the -ScriptBlock parameter on the same line as the command. Do not put it on the line below as you would with an if or while command.

This leads to a the further issue of not spotting that you have not matched opening { and closing } brackets properly, as you are used to the convention of matching their indentation level to pair them up.

Please note that the references to $Event.timestamp in the code. These come from the fact that one of the JSON fields is called timestamp - it is not a method or property of a standard string or array.



来源:https://stackoverflow.com/questions/42149748/powershell-start-job-scriptblock-multi-line-scriptblocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!