【问题标题】:PowerShell: Start-Job -scriptblock Multi line scriptblocks?PowerShell: Start-Job -scriptblock 多行脚本块?
【发布时间】:2018-08-29 07:33:55
【问题描述】:

希望有人可以帮助我弄清楚这是否可能。我有 20 行在 while 循环中扫描日志文件。我需要这与脚本的其余部分并行发生。日志扫描循环将条目传递给 SQLite,其他脚本需要根据这些信息采取行动——因此希望并行运行它们。

如果我使用 Job-Start 命令,那么 -SciptBlock 函数似乎只接受一行命令。我有太多命令要通过管道传输,所以我需要在脚本块中运行多行。

我尝试了几种方法,但以下示例给出的错误最少。我还在 Invoke-Command -ScriptBlock 中进行了尝试,就像在第二个示例中一样 - 两种方式都不会接受多行脚本块。

请问我做错了什么?

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
  }
}

错误如下:

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

【问题讨论】:

    标签: powershell jobs invoke-command start-job scriptblock


    【解决方案1】:

    感谢briantist 帮助我到达那里:)

    使用Start-JobInvoke-Command 时,注意将-ScriptBlock 参数的开头{ 与命令放在同一行。不要像使用ifwhile 命令那样将其放在下面的行中。

    这会导致进一步的问题,即没有发现您没有正确匹配打开 { 和关闭 } 括号,因为您习惯于匹配它们的缩进级别以配对它们。

    请注意代码中对$Event.timestamp 的引用。这些来自这样一个事实,即其中一个 JSON 字段称为 timestamp - 它不是标准字符串或数组的方法或属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      • 2011-04-25
      • 2013-01-17
      • 1970-01-01
      相关资源
      最近更新 更多