Powerhell的部分管道被跳过

时间:2019-03-07 15:48:04

标签: powershell pipeline

每2次迭代都会跳过一部分流水线指令,获取/设置显式变量就可以了。我在这里想念什么?

请注释/取消注释脚本底部的部分,以比较cfg.json中的结果。

param (
    [string]$JSONFname = "cfg.json",
    [string]$Iterations = 300
  )

Function GetCfgData {
    param (
      [string]$JSONFname = "cfg.json",
      [string]$Key = ""
    )
    if (-not (Test-Path $JSONFname)) {
      New-Item -Name $JSONFname > $null
      $JSONData = @{iteration = $Iterations}
      $JSONData | ConvertTo-Json -depth 100 | Out-File $JSONFname
    }
    Write-Host (Get-Content $JSONFname | ConvertFrom-Json).$Key
    return [string](Get-Content $JSONFname | ConvertFrom-Json).$Key
  }

  Function SetCfgData {
    param (
      [string]$JSONFname = "cfg.json",
      [string]$Key = "",
      [string]$Value = ""
    )
      $JSONData = Get-Content $JSONFname | ConvertFrom-Json
      $JSONData.$Key = $Value
      $JSONData | ConvertTo-Json -depth 100 | Out-File $JSONFname
  }

1..100 | foreach {
  # "skipped" case 1
  # GetCfgData -Key "iteration" | ForEach-Object { $val= [int]$_ - 1} | SetCfgData -Key "iteration" -Value $val

  # working case 2
  $iter = GetCfgData -Key "iteration" 
  SetCfgData -Key "iteration" -Value $([int]$iter -1)
}

0 个答案:

没有答案